+2

>> << operator in Python

Please help me to getting clear with << >> operator in Python. Here’s the code that “knocks me out”: x = 5 print(x>>2<<x) And the output is 32. I found that x<<y it’s x*2**2 and that x>>y it’s x//2**y, but it doesn’t work. I can’t get it even mathematically..

8/23/2019 9:23:25 PM

Stanislav M

1 Answer

New Answer

+4

For the studying purposes represent your number as binary: 5 -> 00000101 1. Now shift it right to 2 positions (x>>2) as it is written in first half of your example: 00000101 >>2 -> 00000001 (we 'lost' rightmost '1'). So we've got 00000001 (1). 2. Now shift the result left to 5 positions (as in your example's second half (<<x), assuming that x equals 5: 00000001 << 5 -> 00100000 So we have 00100000 nowm which is 32 in decimal.