Why does OR 0 round numbers in Javascript?

我的未来我决定 提交于 2019-12-04 04:21:14

问题


I'm under the impression that the Number type in Javascript stores any number, integer or float, according to the IEEE floating point standard. If so, then why does bitwise OR-ing a number with 0 round it down?

Playing around with some other bit ops, it appears that when applying bit operations to floating point numbers, the number is first rounded towards 0 and then the bit operations are applied (with the numbers in Two's complement representation rather than IEEE). Is this correct?


回答1:


In ECMAScript 5.1, all bitwise operations will convert the input to a 32-bit integer, and return a 32-bit integer. Regarding the operators ^, & and |, section 11.10 says:

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.

Note that ToInt32 is applied on both sides before the operator is applied.




回答2:


Quote from MDN

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers.

If you didn't treat the numbers like this the bitwise ops wouldn't make much sense, which is why it is done




回答3:


At language level there is only floats, and temporary integers for bitwise operators.

Per spec, a float is turned into a 32-bit integer by doing the abstract operation:

var n = (sign(number) * floor(abs(number))) % pow(2, 32);
if( n >= pow( 2, 31 ) ) {
     return n - pow( 2, 32 );
}
else {
     return n;
}

I must emphasize that this operation is abstract and certainly not done in the above fashion by any engine so don't draw any performance considerations from it. (This goes for any other spec operation too)



来源:https://stackoverflow.com/questions/18219441/why-does-or-0-round-numbers-in-javascript

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