0
What does it mean << and >> in Python?
I can't understand them. Could you please explain?
2 Antworten
+ 1
Those are bitwise operators. The << shifts the bits to the left (which multiplies a value by 2^N) and the >> shifts the bits to the right (which divides a value by 2^N).
To visualize what is happening, think of the number 12 stored in a 4-bit byte. It's representation in memory will be:
Binary: 1 1 0 0
Decimal: 8, 4, 2, 1
If you right shift 12 by 1 (12 >> 1) then all the bits are shifted right one step and you now have the value 6 (a division by 2^1). The binary value of 6 is 0 1 1 0. So the leftmost bits were shifted
from 1 1 0 0 ---> 0 1 1 0.
If you now left-shift 6 by one (6 << 1) those bits are shifted back to their original place (turning into a multiplication of 6 by 2^1) which is 12, and the binary representation is back to 1 1 0 0.
From 0 1 1 0 ---> 1 1 0 0.
If we right-shift 12 by 2 (12 >> 2) we're moving all the bits 2 steps to the right and the value is now 0 0 1 1 in binary, or the decimal number 3. It's the same as 12 / (2 ^ 2) = 3
There is a danger that we may shift the bits too far left or right so the bit may be shifted off one end.
If we right-shift the number 3 we'll drop one bit. A left-shift would not return the lost bit instead it would shift the rightmost bit left and a 0 will fill the place of the lost bit.
0 0 1 1 ---> 0 0 0 1
0 0 0 1 ---> 0 0 1 0