6

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?

Erik
  • 14,060
  • 49
  • 132
  • 218

2 Answers2

6

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

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214
  • Thanks for the answer. Could you explain do I have mistake in my approach? – Erik Jan 20 '16 at 10:17
  • @Erik, I think `sjrd` have one good answer for that, also more details, please refer to this [question](http://stackoverflow.com/questions/1908492/unsigned-integer-in-javascript) – zangw Jan 20 '16 at 10:32
5

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);
sjrd
  • 21,805
  • 2
  • 61
  • 91