Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...