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?
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 signed32-bit
integers (converted from the native Number storage of double-precision float). So1<<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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With