+ 2

How does this work?

x = 5 print(x>>2<<x) #32

25th Apr 2019, 3:06 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
4 odpowiedzi
+ 7
1. Write 5 in binary with 8 bits. This is because computers take 8 bits. 00000101 2. x>>2 means add 2 zeroes on your left to shift the value to the right. It has to remain 8 bits, so 01 at the right end is removed. 00000001 3. 2<<x means add 5 zeroes on your right to shift the value to the left. It has to remain 8 bits, so the extra zeroes on the left end is removed. 00100000 4. Convert the obtained binary value to decimals. And your answer will be 32.
25th Apr 2019, 4:08 AM
silentlearner
silentlearner - avatar
+ 1
x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y. x >> y Returns x with the bits shifted to the right by y places. This is the same as dividing xby 2**y.
25th Apr 2019, 3:41 AM
Edwin
Edwin - avatar
+ 1
Thanks! Edwin
25th Apr 2019, 4:01 PM
Thimira Rathnayake
Thimira Rathnayake - avatar
+ 1
Thanks! silentlearner
25th Apr 2019, 4:01 PM
Thimira Rathnayake
Thimira Rathnayake - avatar