Why is JavaScript bitwise OR behaving strangely?

别等时光非礼了梦想. 提交于 2019-11-28 03:54:29

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/9329899/why-is-javascript-bitwise-or-behaving-strangely

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