我正在尝试编写一个函数来返回小于 Javascript 限制 (2^53)-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
方法二:
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
我认为这两种方法都无法精确解决问题。
谁能推荐一种适用于 0 -> 2^53-1 之间数字的替代方法
谢谢。
最佳答案
你可以这样做:
function bitSize(num) {
return num.toString(2).length;
}
toString()
Number
的方法将基数作为可选参数。
这里有一些 tests .适用于 Chrome、Safari、Opera 和 Firefox。无法访问 IE,抱歉。
关于javascript - 表示数字的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3081271/