Search code examples
javascriptbitwise-operators

Bitwise operations on large numbers


This works as expected:

> 0b1111
15
> 0b1111 & 0b1111
15

But this doesn't:

> 0b11111111111111111111111111111111
4294967295
> 0b11111111111111111111111111111111 & 0b11111111111111111111111111111111
-1

What's going on here? And how can I safely perform bitwise operations on large (up to 2^32) numbers in Javascript?

Update: This is below Number.MAX_SAFE_INTEGER so I don't believe there should be a loss of precision.


Solution

  • What's going on here?

    JavaScript's bitwise operators will interpret the result as a signed 32-bit number (one exception is the >>> operator), but apart from that, the result is correct.

    And how can I safely perform bitwise operations on large (up to 2^32) numbers in Javascript?

    Apply >>> 0 to the result so the result is interpreted as an unsigned 32 bit number:

    let res = (0b11111111111111111111111111111111 
                & 0b11111111111111111111111111111111) >>> 0;
    
    console.log(res);