简体   繁体   中英

Why is JavaScript bitwise OR behaving strangely?

In JavaScript, it seems:

(4294958077 | 0) == -9219

Why is it not 4294958077 ?

It suggests that there's some sort of overflow kicking in (although as I understand it a JavaScript Number type's range is +/- 9007199254740992 so that's odd in itself.)

Even if it was an overflow, surely

(4294958077 | 0) == 4294958077

should evaluate as true - but it doesn't.

Help please

It has nothing to do with floating point type or overflows. It returns -9219 because the standard mandates it, as all binary bitwise operations have to be done using signed 32-bit integers (ECMA-262 §11.10).

The production A : A @ B , where @ is one of the bitwise operators in the productions above, is evaluated as follows:

  1. Let lref be the result of evaluating A .
  2. Let lval be GetValue( lref ).
  3. Let rref be the result of evaluating B .
  4. Let rval be GetValue( rref ).
  5. Let lnum be ToInt32( lval ).
  6. Let rnum be ToInt32( rval ).
  7. Return the result of applying the bitwise operator @ to lnum and rnum . The result is a signed 32 bit integer.

4294958077 converted to a signed 32-bit integer (using the algorithm in ECMA-262 §9.5) is -9219, and 0 is still 0, so the bitwise-or will return -9219.

All numbers in Javascript are 64bit floating point numbers. Bitwise operations on floats are an edge case, so internally those floats are temporarily converted to a 32bit int, then the bitwise operation is performed - hence your overflow.

JavaScript bitwise numbers are stored as signed 64-bit floats, ie you only have 32-bits to use for the integer, which you have exceeded, so it's gone weird by converting it to an integer as best it can and then doing the operation.

More information here (especially the 'beyond 32-bit' section) but no real solution, so unfortunately, you'll need to work around it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM