Reputation: 79
The case is the following:
/// returns 406913024, but should 417018740736
alert(6363201 << 16);
What is wrong? I tried the same in ruby and it returns the correct value (http://www.miniwebtool.com/bitwise-calculator/bit-shift/?data_type=10&number=6363201&place=16&operator=Shift+Left)
Upvotes: 0
Views: 1028
Reputation: 239493
Quoting from MDN Left Shift Operator
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
Quoting 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.
Binary of 6363201
is 11000010001100001000001
.
When you left shift 6363201 << 16
, it becomes 417018740736
which in binary is 110000100011000010000010000000000000000
Now, 32 bits from the least significant bits are retained, the actual bits retained are 00011000010000010000000000000000
which corresponds to 406913024
Upvotes: 4
Reputation: 4971
In JavaScript, you are dealing with 32-bit numbers.
6363201 << 16
results in 110000100011000010000010000000000000000
, which are 39 bits. Shedding off the first 7 bits (since you are shifting from right to left, you end up with 00011000010000010000000000000000
, which a (binary) parseInt
of it will show you that is 406913024, not 417018740736.
Upvotes: 2