Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a bitwise and on numbers greater than 2^32 in Javascript?

Tags:

javascript

For example, how to get the correct answer to 137438953472 & 137438953472?

Javascript returns 0 if operands are between 2^32 and 2^53(max int).

like image 813
Alena Avatar asked Apr 06 '12 15:04

Alena


1 Answers

Ok here's what I came up with, only tested with unsigned integers < 2^53:

edit: nailed a bug when partial results are interpreted as signed

function and( op1, op2 ) {

    var mod = Math.pow( 2, 32 ),
        op1mod = op1 % mod,
        op2mod = op2 % mod,
        op164to32,
        op264to32,
        res32, res64, res;

        op1 -= op1mod;
        op2 -= op2mod;

        res32 = ( op1mod & op2mod ) >>> 0;


        op164to32 = op1 / mod;
        op264to32 = op2 / mod;
        res64 = ( op164to32 & op264to32 ) >>> 0;

        res = res64 * mod + res32;
        return res;
}

and( 137438953473, 137438953473 )
//137438953473
and( 137439087606, 137438953473)
//137438953472
and( 0xCAFECAFECAFE, 0xBABEBABEBABE )
//152550976162494

results confirmed to be correct with windows 64 bit calculator :P

like image 127
Esailija Avatar answered Oct 21 '22 07:10

Esailija