Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does shift operation whose right operand is over 31 do, in Javascript?

Tags:

javascript

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
like image 853
Константин Ван Avatar asked Dec 28 '17 21:12

Константин Ван


1 Answers

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.

like image 143
Herohtar Avatar answered Oct 17 '22 07:10

Herohtar