I need to bitwise shift a value 64 times in JavaScript. But JavaScript starts rounding after 32
.
For example:
for(var j = 0; j < 64; j++)
{
mask = mask << 1;
console.log(mask);
}
This prints value from 0
to 1073741824
but then rounds of and starts printing 0
.
Description. This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.
The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.
The left shift operator ( << ) shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
In simple words >>> always shifts a zero into the leftmost position whereas >> shifts based on sign of the number i.e. 1 for negative number and 0 for positive number. For example try with negative as well as positive numbers.
"In Java, the bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow. JavaScript is rarely used for doing bit manipulation." - Douglas Crockford, Javascript: The Good Parts
The point is that you don't really have any reason to use bitwise operators. Just multiply or divide by 2^numbits.
Your code should be:
for(var j = 0; j < 64; j++) {
mask = mask * 2;
console.log(mask);
}
Or generally:
function lshift(num, bits) {
return num * Math.pow(2,bits);
}
You get the idea.
JavaScript stores all its numbers as 64 bit initally, but as soon as you start using bitwise operators the interpreter converts the number to a 32 bit representation..
Bitwise operators are a bit hacky in JS and so annoyingly you will probably have to do something a bit more clever, like write your own 64 bit functions.
With BigInt you can use bitwise operators, except >>>
.
For example:
console.log(1n << 32n); // 4294967296n
console.log(1n << 40n); // 1099511627776n
console.log((1n << 40n).toString(2)); // 1 00000000 00000000 00000000 00000000 00000000
BigInt is a 64-bit signed integer.
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