Why is this code giving 32 for the bits in a number (and not 53)?
javascript
Solution
Bitwise operations are specified by the JavaScript/ECMAScript standard to truncate the number to 31 bits (round towards zero, take the modulus with 232, and interpret the most significant bit as a two's-complement sign) before anything else happens. So you need to recode it using plain arithmetic.
This is in part because FPUs which handle fractional numbers may not implement bitwise operations, at the logic circuit level.
The most naive way of testing is `for ( var i = 0; i != i + 1; ++ i ) ;` but that crashed Firefox when I tried it. (Was expecting a timeout, but nope!) The slightly more specific one-liner
for ( var i = 1, j = 0; i != i + 1; i *= 2, ++ j ) ;
does yield `j == 53`.
As an aside, note that the idiom `x | 0` for rounding doesn't work with numbers greater or equal to 231. So `Math.round` is generally better.
Problem
I'm using this code to try to find out how many bits are in a number. The hex number below has all bits turned on. ``` for (var i = 0x1FFFFFFFFFFFFF, m = 0; i & 1; ++m, i >>>= 1); ``` For some reason printing `m` gives 32, but in a SO post I read the following: All numbers in JavaScript are actually IEEE-754 compliant floating-point doubles. These have a 53-bit mantissa which should mean that any integer value with a magnitude of approximately 9 quadrillion or less will be represented accurately. Unless I'm implementing this incorrectly, I don't understand why printing `m` gives 32 when there are supposed to be 53 bits. Can someone please explain?