javascript64-bitbit-manipulation

How to do bitwise AND in javascript on variables that are longer than 32 bit?


I have 2 numbers in javascript that I want to bit and. They both are 33bit long

in C#:

 ((4294967296 & 4294967296 )==0) is false

but in javascript:

 ((4294967296 & 4294967296 )==0) is true

4294967296 is ((long)1) << 32

As I understand it, it is due to the fact that javascript converts values to int32 when performing bit wise operations.

How do I work around this? Any suggestions on how to replace bit and with a set of other math operations so that bits are not lost?


Solution

  • You could split each of the vars into 2 32-bit values (like a high word and low word), then do a bitwise operation on both pairs.

    The script below runs as a Windows .js script. You can replace WScript.Echo() with alert() for Web.

    var a = 4294967296;
    var b = 4294967296;
    
    var w = 4294967296; // 2^32
    
    var aHI = a / w;
    var aLO = a % w;
    var bHI = b / w;
    var bLO = b % w;
    
    WScript.Echo((aHI & bHI) * w + (aLO & bLO));