Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 589
Erik Avatar asked Jan 20 '16 10:01

Erik


2 Answers

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

like image 151
zangw Avatar answered Sep 19 '22 11:09

zangw


Most bitwise operations are specified as converting their operands to signed 32-bit integers. It is perfectly correct to use bit 31, but yes, you'll get negative values. Usually it doesn't matter if you're doing bitwise operations anyway, since all you (should) care about is the bit pattern, not the decimal value of the number.

If you do want a positive value back, you can convert it back with >>> 0, because >>> is specified to convert its operands to unsigned 32-bit integers.

console.log((0 | 1 << 31) >>> 0);
like image 45
sjrd Avatar answered Sep 19 '22 11:09

sjrd