Search code examples
javascriptbitwise-operatorsbit-shift

Is it correct to set bit 31 in javascript?


When I try to set 31 bit 0 | 1 << 31 I get the following result:

console.log(0 | 1 << 31); // -2147483648

Which is actualy:

console.log((-2147483648).toString(2)) // -10000000000000000000000000000000

Is it correct to set 31 bit or should I restrict to 30 to prevent negative values?


Solution

  • Refer to ECMA5 that the bitwise operators and shift operators operate on 32-bit ints, so in that case, the max safe integer is 2^31-1, or 2147483647.

    Here is one explanation.

    The << operator is defined as working on signed 32-bit integers (converted from the native Number storage of double-precision float). So 1<<31 must result in a negative number.

    The only JavaScript operator that works using unsigned 32-bit integers is >>>. You can exploit this to convert a signed-integer-in-Number you've been working on with the other bitwise operators to an unsigned-integer-in-Number:

    (1<<31)>>>0