Search code examples
javascriptbitwise-operators

Negative values after bitwise OR operation between two int values


I am trying to perform a bitwise OR operation between two numbers: 650510336 and 2147483648 (650510336 | 2147483648)

As a result, I get the negative value: -1496973312 instead of ‭2797993984.

I thought I have an issue in my code, but if you send this command to the console in your browser, you can easily reproduce it.

console.log(650510336 | 2147483648)

Why doesn't this output 2797993984?


Solution

  • All bitwise operators in JavaScript, when used on numbers, treat their operands as/produce results of 32-bit signed integers… except for the >>> operator.

    Since you want unsigned math, use an otherwise no-op logical right shift to reinterpret the signed result as unsigned:

    console.log((650510336 | 2147483648) >>> 0)