Javascript 如何获取32位整数的位长度

Javascript 如何获取32位整数的位长度,javascript,integer,bit-manipulation,Javascript,Integer,Bit Manipulation,我在JavaScript中尝试了几种变体,但没有一种能达到预期的效果 assert(countIntegerBits(4,3)//100 assert(countIntegerBits(8),4)//1000 assert(countIntegerBits(20),5)//10100 断言(countIntegerBits(100),7)//1100100 // https://stackoverflow.com/questions/43122082/efficiently-count-the

我在JavaScript中尝试了几种变体,但没有一种能达到预期的效果

assert(countIntegerBits(4,3)//100
assert(countIntegerBits(8),4)//1000
assert(countIntegerBits(20),5)//10100
断言(countIntegerBits(100),7)//1100100
// https://stackoverflow.com/questions/43122082/efficiently-count-the-number-of-bits-in-an-integer-in-javascript
函数countIntegerBits(整数){
变量长度=0
while(整数=数学地板(整数)){
if(整数&1){
长度++
}
整数/=2
}
返回长度
}
函数countIntegerBits(整数){
//变量长度=0
//while(整数!==0){
//长度+=计数整数比特数32(整数| 0)
//整数/=0x100000000
// }
//返回长度
//
//或许是这样:
// https://gist.github.com/everget/320499f197bc27901b90847bf9159164#counting-32位整数中的位
}
函数countIntegerBits32(整数){
整数=整数-((整数>>1)和0x5555)
整数=(整数和0x33333333)+(整数>>2)和0x33333333)
返回((整数+(整数>>4)&0xF0F)*0x1010101)>>24
}
函数countStringBits(字符串){
//看起来这个/8就足够了
// https://codereview.stackexchange.com/questions/37512/count-byte-length-of-string
变量长度=0;
对于(变量i=0;i长度+=c<(1自然对数(井,对数到任何基准)和对数到另一基准之间存在关系。要获得基准-2对数:

const log2 = n => Math.log(n) / Math.log(2);
在添加1后,您可能希望进行四舍五入:

const bits = n => Math.floor(log2(n) + 1);

自然原木(任何基地的原木)和另一基地的原木之间存在关系。要获取base-2原木:

const log2 = n => Math.log(n) / Math.log(2);
在添加1后,您可能希望进行四舍五入:

const bits = n => Math.floor(log2(n) + 1);

为什么不直接拿base-2日志进行汇总呢?我不知道怎么做,我没有数学方面的CS学位或背景。
math.log(n)/math.log(2)
So
1+math.floor(math.log(integer)/math.log(2))
。在我的机器
math.log上通过了上面所有的断言(1为什么不直接拿base-2日志进行汇总呢?我不知道怎么做,我没有数学方面的CS学位或背景。
math.log(n)/math.log(2)
So
1+math.floor(math.log(integer)/math.log(2))
。我的机器
math.log(1oops忘了
math.ceil()
JavaScript有
Math.log2(n)
,所以甚至可能只是
Math.ceil(Math.log2(n))
。对于
4
它给出2而不是3。是的
Math.log2()
很棒,但在IE11中不起作用。还有常量
Math.LN2
来避免调用
Math.log(2)
Oh-Oh,对了;您添加了1,然后添加了
Math.floor()
。看,这是一件愚蠢的事情,我的编程生活中令人尴尬的一部分一直致力于修复。oops忘记了
Math.ceil()
JavaScript有
Math.log2(n)
,所以甚至可能只是
Math.ceil(Math.log2(n))
对于
4
它给出的是2而不是3。是的
Math.log2()
很好,但在IE11中不起作用。还有常量
Math.LN2
可以避免调用
Math.log(2)
哦哦,对了;添加1,然后
Math.floor()
。这是我编程生涯中尴尬的一部分一直致力于解决的愚蠢问题。