So I was trying to make some functions in javascript that shift and manipulate the bits of numbers. However, I found the following behavior in my console
> var a = 1;
undefined
> a <<= 3
8
> a <<= 55
67108864
> a <<= 40
0
My question is, if the value gets larger above a certain point, why does the number go back to zero? In other languages like python the number just keeps getting larger, or a notation is used to hold the value of the number. Or, an overflow error is shown. Why does JavaScript simply reset the number to zero?
According to the documentation:
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 the case of your 55 (0x110111) and 40 (0x101000) you are bit-shifting by 23 (0x10111) and 8 (0x01000) respectively:
> var a = 1;
undefined
> a <<= 3
8
> a <<= 23
67108864
> a <<= 8
0
Note that although these aren't the same as what you wrote, the answers are the same as for why you get 0, consider the bits:
> var a = 1;
undefined
> a <<= 3 + 23
67108864 // 0x000[00000100000000000000000000000000]
> a <<= 8
0 // 0x100[00000000000000000000000000000000]
The square brackets denote what value is actually used to determine the value of the number, the section to the left is discarded. As you can see you've bitshifted the 1 all the way off the left of the number resulting in 0 being left over.
Note the below snippet, after reaching the 32 shift mark all results are 0:
var a = 1;
for(var i = 1; i < 40; i++){
a <<= 1;
console.log(i, a);
}
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