What exactly does a shift operation, the right operand of which exceeds 31, in Javascript?

I know that the operands of a bitwise operation are treated as 32-bit integers in Javascript. So I thought it would be zero if I make << 32 for integer values. But it worked as if it was << 0 . Why did it work? What exactly does a shift operation, the right operand of which exceeds 31, in Javascript?

 0b00000000000000000000000000000001 << 32 // 1 0b00000000000000000000000000000001 << 33 // 2 0b00000000000000000000000000000001 << 34 // 4 0b00000000000000000000000000000001 >> 30 // 0 0b00000000000000000000000000000001 >> 31 // 0 // Something weird is happening....... 0b00000000000000000000000000000001 >> 32 // 1 0b00000000000000000000000000000001 >> 33 // 0 
+7
javascript
source share
1 answer

Truncates the binary representation of the correct operand.

From the documentation for Bitwise shift operators :

The shift operators convert their operands to 32-bit integers in orthogonal order and return the result of the same type as the left operand. The correct operand must be less than 32, but if not only low five bits will be used.

So in your example 32 there is 0b100000 . Since it takes only the least significant five bits, you are left with 0b00000 , so it shifts the number by 0 . Again, 33 is 0b100001 , and the lower five bits are 0b00001 , so it shifts the number by 1 . And so on.

+8
source share

All Articles