javascript - 表示数字的位数

标签 javascript bit-manipulation bit

我正在尝试编写一个函数来返回小于 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/

相关文章:

javascript - Vuejs - 将原始 html 链接渲染到 <router-link>

javascript - Passport-Facebook 身份验证未为所有 Facebook 帐户提供电子邮件

javascript - jQuery 数据表 : Unsorted View

python - Python 中的位掩码

c++ - 4 个有符号字节打包成 32 位无符号

c - 移位不适用于变量声明赋值单行

vhdl - 如何确定 VHDL 中是否设置了 STD_LOGIC_VECTOR 中的多于一位

Java位比较,bitset?

javascript - 为连接到 websocket 服务器的客户端生成唯一 ID

c++ - 根据标准,整数中的值表示位数?