Introduction To Bitwise Operators 6/14 Explanation?


#1

A bit confused with the explanation:

An easy way to look at bit shifting is to visually move the bits in the specified direction by the specified amount. If we have a bit string of 1000 and shift right by 1, we end up with 0100 . Shift right by another 1 and we get 0010 .
If we have 0010 and shift right by 2, however, we lose our bit! And there’s no getting it back after it falls of the beginning or end, so be careful! We’d end up with 0000 .
So given some variable like my_bit_string = 0b1000 , we can get 0b0001 by doing my_bit_string = my_bit_string >> 3 .

That part:

If we have 0010 and shift right by 2, however, we lose our bit! And there’s no getting it back after it falls of the beginning or end, so be careful!

In our case:

shift_left = 0b1

We do this shift_left = shift_left << 2

And we get 0b100

But why? Isn’t 1 supposed to fall of at the beginning OR end like they mention in the explanation, so that we end up with 0 instead of 4(0b100)?


#2

Right shift is equivalent to floor dividing by 2.

10 >> 1  => 1    # 2 // 2 == 1
1 >> 1   => 0    # 1 // 2 == 0

Any odd number will have the 1’s bit set.

1     => 1
11    => 3
101   => 5
111   => 7
1001  => 9
1011  => 11
1101  => 13
1111  => 15

It follows that if we shift right by one bit, we lose the 1.

1 >> 1     => 0
11 >> 1    => 1
101 >> 1   => 2
111 >> 1   => 3
1001 >> 1  => 4
1011 >> 1  => 5
1101 >> 1  => 6
1111 >> 1  => 7

Notice how the result is the quotient of n // 2?


#3

Oh so it only applies when we right shift…


#4

Correct. When we shift one bit left the number grows by a factor of 2.

1 << 1     => 2
1010 << 1  => 20

#5

Oh I see, thanks. :wink:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.