Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 251
hchau Avatar asked Sep 03 '25 09:09

hchau


1 Answers

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.

like image 93
bfavaretto Avatar answered Sep 05 '25 01:09

bfavaretto