表示数字的位数 [英] Number of bits to represent a number
问题描述
我正在尝试编写一个函数来返回一个正整数的位数,小于(2 ^ 53)-1的Javascript限制。但是我遇到精度问题,并且想避免使用大整数库。
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.
方法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
方法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.
任何人都可以建议一种替代方法,适用于0 - > 2 ^ 53-1之间的数字
Can anyone suggest an alternative method that will work for numbers between 0 -> 2^53-1
谢谢。
推荐答案
你可以这样做:
function bitSize(num) {
return num.toString(2).length;
}
toString()
数字$的方法c $ c>将基数作为可选参数。
The toString()
method of Number
takes the radix as an optional argument.
这里有一些测试的。适用于Chrome,Safari,Opera和Firefox。无法访问IE,抱歉。
Here are some tests. Works on Chrome, Safari, Opera, and Firefox. No access to IE, sorry.
这篇关于表示数字的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!