Skip to content

Instantly share code, notes, and snippets.

@nemisj
Created May 13, 2015 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nemisj/89c9ef368142b440b367 to your computer and use it in GitHub Desktop.
Save nemisj/89c9ef368142b440b367 to your computer and use it in GitHub Desktop.
How to do bitwise AND in javascript on variables that are longer than 32 bit
// taken from http://stackoverflow.com/questions/3637702/how-to-do-bitwise-and-in-javascript-on-variables-that-are-longer-than-32-bit
function BitwiseAndLarge(val1, val2) {
var shift = 0, result = 0;
var mask = ~((~0) << 30); // Gives us a bit mask like 01111..1 (30 ones)
var divisor = 1 << 30; // To work with the bit mask, we need to clear bits at a time
while( (val1 != 0) && (val2 != 0) ) {
var rs = (mask & val1) & (mask & val2);
val1 = Math.floor(val1 / divisor); // val1 >>> 30
val2 = Math.floor(val2 / divisor); // val2 >>> 30
for(var i = shift++; i--;) {
rs *= divisor; // rs << 30
}
result += rs;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment