+ 1

How does this code work? print(5>>2) (Python)

print (5>>2) -> Output 1

5th Jan 2025, 4:14 PM
David
David - avatar
7 Réponses
+ 5
David this code explains the shift right bitwise operator https://sololearn.com/compiler-playground/cc8GLRo2i21c/?ref=app additionally you might like this to explain Binary and bitwise shift left and right ... https://www.sololearn.com/Discuss/2265151/?ref=app
5th Jan 2025, 5:10 PM
BroFar
BroFar - avatar
+ 2
RuntimeTerror That is NOT quite how right bitwise shift operator works. Every number is represented in computer as binary number. Without getting into overflow and negative number representation: Left shift bitwise operator << Move each binary digit left and add 0 in least significant spot. Equivalent to multiplying by 2. Right shift bitwise operator >> Move each binary digit right and add 0 to most significant spot. Equivalent to divide by 2 and drop any remainder. 5 represented as binary is 00000101. 5>>1 would be 00000010 which is binary for 2 5>>2 would be 00000001 which is binary for 1 Similarly 5<<1 would be 00001010 which is binary for 10
21st Jan 2025, 5:32 AM
Shardis Wolfe
+ 1
>> 2 means 2 raised to power of two (division) So, it is 5/4 = 1.25. In bit operation, all result must be an integer so you get 1. NOTE >> 3 means 2 raised to power of 3 (division) >> 4 means 2 raised to power of 4 (division) And so on The opposite is multiplication (<<)
5th Jan 2025, 7:33 PM
RuntimeTerror
RuntimeTerror - avatar
+ 1
Output 1
7th Jan 2025, 6:38 AM
Netik Singh
Netik Singh - avatar
+ 1
Output 1
7th Jan 2025, 10:06 AM
Lamborghini
Lamborghini - avatar
0
Shardis Wolfe you speak a whole lot of nonsense with that
21st Jan 2025, 6:37 AM
RuntimeTerror
RuntimeTerror - avatar
0
Then you obviously did not read it. Your loss.
21st Jan 2025, 11:21 AM
Shardis Wolfe