0

Bitwise operators >> and << in Python

In one of the quiz challenges, I got the following question: What is the output of this code? x = 5 print (x >> 2 << x) The answer was 32. I don't really understand, how this works... Additionally I would have expected that it would print 0s and 1s, why is it converted back to an integer? Thank you! Any help is appreciated :)

16th May 2017, 8:05 PM
PwnySQL
2 Antworten
+ 2
x = 5 = 0b101 >> 2 # shifted 2 bits to the right it becomes 0b1 = 1 << x # shifted 5 bits to the left. x is substituted here before shift operations begin that's why it is shifted 5 bits # it becomes 0b100000 = 32 you was expecting it to print 0b100000 but the function print() outputs such numbers in decimal by default. That's why 32 is printed out.
16th May 2017, 8:36 PM
Ulisses Cruz
Ulisses Cruz - avatar
0
The >> and << operators represent shifting the bit equivalent to the left or right of a number or character. For example: 10 in binary is: 1010 10 shifted right (>>) is: 0101 0101 in binary is: 5
16th May 2017, 8:25 PM
Sapphire