Jason Gooner - 1 year ago 65

Javascript Question

I'm trying to write a function to return the number of bits a positive integer less that the Javascript limit of (2^53)-1 is. However im being hit by precision problems, and want to avoid big integer libraries.

Method 1:

`function bitSize(num)`

{

return Math.floor( Math.log(num) / Math.log(2) ) + 1;

}

Pass: bitSize( Math.pow(2, 16) -1 ) = 16

Pass: bitSize( Math.pow(2, 16) ) = 17

Fail (Should be 48): bitSize( Math.pow(2, 48) -1 ) = 49

Pass: bitSize( Math.pow(2, 48) ) = 49

Method 2:

`function bitSize(num)`

{

var count = 0;

while(num > 0)

{

num = num >> 1;

count++;

}

return count;

}

Pass: bitSize( Math.pow(2, 16) -1 ) = 16

Pass: bitSize( Math.pow(2, 16) ) = 17

Fail (Should be 48): bitSize( Math.pow(2, 48) -1 ) = 1

Fail (Should be 49): bitSize( Math.pow(2, 48) ) = 1

Both methods fail to precision issues I think.

Can anyone suggest an alternative method that will work for numbers between 0 -> 2^53-1

Thanks.

Answer Source

You can do:

```
function bitSize(num) {
return num.toString(2).length;
}
```

The `toString()`

method of `Number`

takes the radix as an optional argument.

Here are some tests. Works on Chrome, Safari, Opera, and Firefox. No access to IE, sorry.