Why is JavaScript bitwise OR behaving strangely?

五迷三道 提交于 2019-11-29 10:47:52

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, i.e. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!