Reputation: 195
I am trying to understand bitwise operators in Python 2.7 (<<
, >>
, &
, |
, ~
and ^
), so my question is: what is the interpreter really seeing and executing? When:
>>> 3 >> 0
3
>>> 3 >> 1
1
and why
>>> 3 >> 2
0
and after that if you increment the second number by one the answer will continue to be 0
.
They treat it as if it were a string of bits, written in twos-complement binary. But I do not understand what happens here.
Upvotes: 0
Views: 52
Reputation: 5866
Have a look at the binary representation of these numbers and imagine that there are infinite zeroes to the left:
...0000011 = 3
Now, what >>
does is it shifts the binary representation to the right. This is the same as deleting the last digits:
If you shift by 0
places, nothing changes. Therefore, 3 >> 0
is 3.
If you shift by 1
place, you delete the last binary digit:
...0000011 >> 1 = ...000001 = 1
Therefore, 3 >> 1
is 1.
If you shift by 2
or more places, all of the binary ones will be deleted and you are left with only zeroes:
...0000011 >> 2 = ...00000 = 0
This is why 3 >> 2
(or more than 2) is always 0.
Upvotes: 5