+ 5
Why returns the below code 32?
x=5 print(x>>2<<x)
12 Answers
+ 7
Paweł Malewicz
x=5 is x=00000101(bin)
x>>2 is 00000001(bin) or 1(dec)
(x>> 2)<<x is 1(dec)<<5(dec)
So it is 000100000(bin) or 32(dec)
+ 9
Paweł Malewicz
think about it this way:
i will add parentheses for a clear view:
val << num = val * (2 ** num)
val >> num = val // (2 ** num)
5 >> 2 << 5
means:
5 >> 2 = 5 // 2**2 = 5 // 4 = 1
1 << 5 = 1 * 2**5 = 1 * 32 = 32
+ 3
Petr
9 >> 2 = 9 // 2**2 = 9 // 4 = 2
2 << 9 = 2 * 2**9 = 2 * 512 = 1024
9>>2<<9 = 1024 😃
+ 3
Sebastian Pacurar Super! to summarize
:)
https://code.sololearn.com/cJdxt54wL6Ey/?ref=app
+ 2
Paweł Malewicz :)) it was a long, hard day:)). I correct. Thanks
+ 1
x>>2: shifts 5 (101) two bits to the right, so that you get 1. The 01 from the end of 5 are cut off.
...<<x: shifts the 1 five bits to the left, so that we get 32 (100000).
+ 1
Thank you guys! Now it's clear! 😀Petr, in your comments should be "x=5 is x=00000101" and in the end "it is 00100000".
+ 1
You're welcome. Thank you again!
+ 1
Sebastian Pacurar
if we choose your path, what will be the result for x = 9? :)
0
Why shifts five bits to the left instead of two?
0
You are shifting the left part (x>>2) with the amount of x (5) to the left. Read it from left to right.
0
>> (bitwise left shit)
>>x
is same as dividing by 2^x
<<(bitwise right shift)
<<x
is same as multiplying with 2^x
1*2^5=32