+ 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..

23rd Aug 2019, 9:23 PM
Stanislav M
Stanislav M - avatar
1 Respuesta
+ 5
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.
23rd Aug 2019, 9:38 PM
strawdog
strawdog - avatar