10

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).

Dennis
  • 14,264
  • 2
  • 48
  • 57
Alena
  • 179
  • 1
  • 10
  • Just to clarify, you are looking to _actually_ do a bitwise "and" operation, as signified by the `&`, correct? – cdeszaq Apr 06 '12 at 15:39
  • 1
    [This answer](http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t) may be of interest to you. > bitwise operators and shift operators operate on 32-bit ints. And 2^53 seems to be a 64 bit value. – Elliot Bonneville Apr 06 '12 at 15:40

1 Answers1

8

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

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Yeah, I was wondering about your original (deleted) answer. I upvoted it, even though it looked like it would produce the wrong result. – Robert Harvey Apr 06 '12 at 16:02
  • Might need more testing, please comment here if you find it giving a wrong result with unsigned < 2^53 – Esailija Apr 06 '12 at 16:07
  • it could be written a bit easier(at least for me): `((Math.floor(operand1/i32) & Math.floor(operand2/i32))*i32 + ((operand1%i32) & (operand2%i32))` where i32 = 4294967296; (2^32). – Alena Apr 06 '12 at 16:12
  • @Alena sure, also there is a bug here so it's still not fully working – Esailija Apr 06 '12 at 16:14
  • what bug? no Math.floor()? I also desided to edit your answer before accepting, because i think its way simplier this way. – Alena Apr 06 '12 at 16:26
  • @Alena I explained the bug in "edit:". Yours gives `var i32 = 4294967296; ((Math.floor(0xCAFECAFECAFE/i32) & Math.floor(0xBABEBABEBABE/i32))*i32 + ((0xCAFECAFECAFE%i32) & (0xBABEBABEBABE%i32))); //152546681195198, correct is: 152550976162494` – Esailija Apr 06 '12 at 16:27