bitwise AND in Javascript with a 64 bit integer

前端 未结 5 1975
我在风中等你
我在风中等你 2020-11-27 19:13

I am looking for a way of performing a bitwise AND on a 64 bit integer in JavaScript.

JavaScript will cast all of its double values into signed 32-bit integers to do

5条回答
  •  眼角桃花
    2020-11-27 20:05

    Javascript doesn't support 64 bit integers out of the box. This is what I ended up doing:

    1. Found long.js, a self contained Long implementation on github.
    2. Convert the string value representing the 64 bit number to a Long.
    3. Extract the high and low 32 bit values
    4. Do a 32 bit bitwise and between the high and low bits, separately
    5. Initialise a new 64 bit Long from the low and high bit
    6. If the number is > 0 then there is correlation between the two numbers

    Note: for the code example below to work you need to load long.js.

    // Handy to output leading zeros to make it easier to compare the bits when outputting to the console
    function zeroPad(num, places){
        var zero = places - num.length + 1;
      return Array(+(zero > 0 && zero)).join('0') + num;
    }
    
    // 2^3 = 8
    var val1 = Long.fromString('8', 10);
    var val1High = val1.getHighBitsUnsigned();
    var val1Low = val1.getLowBitsUnsigned();
    
    // 2^61 = 2305843009213693960
    var val2 = Long.fromString('2305843009213693960', 10);
    var val2High = val2.getHighBitsUnsigned();
    var val2Low = val2.getLowBitsUnsigned();
    
    console.log('2^3 & (2^3 + 2^63)')
    console.log(zeroPad(val1.toString(2), 64));
    console.log(zeroPad(val2.toString(2), 64));
    
    var bitwiseAndResult = Long.fromBits(val1Low & val2Low, val1High & val2High, true);
    
    console.log(bitwiseAndResult);
    console.log(zeroPad(bitwiseAndResult.toString(2), 64));
    console.log('Correlation betwen val1 and val2 ?');
    console.log(bitwiseAndResult > 0);
    

    Console output:

    2^3

    0000000000000000000000000000000000000000000000000000000000001000

    2^3 + 2^63

    0010000000000000000000000000000000000000000000000000000000001000

    2^3 & (2^3 + 2^63)

    0000000000000000000000000000000000000000000000000000000000001000

    Correlation between val1 and val2?

    true

提交回复
热议问题