I know that operands of bitwise operation are treated as 32-bit integers in Javascript. So I thought that it would be zero'd out if I do << 32
on integer values. But it worked as if it's << 0
. For what reason is it worked in that way? What exactly does shift operation whose right operand is over 31 do, 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
It truncates the binary representation of the right operand.
From the documentation for Bitwise Shift Operators:
Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.
So in your example, 32
is 0b100000
. Since it only takes the lowest five bits you're left with 0b00000
, so it shifts the number by 0
. Again, 33
is 0b100001
and the lowest five bits are 0b00001
, so it shifts the number by 1
. And so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With