JavaScript: Bitwise shift of long long number
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
.
"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.