Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

bit manipulation - Why does OR 0 round numbers in Javascript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...