在javascript中获取数字的最低有效位的最有效方法是什么? [英] What's the most efficient way of getting position of least significant bit of a number in javascript?
问题描述
我有一些数字,我需要获取它们的低位在0位应该移位多少.
I got some numbers and I need to get how much they should be shifted for their lower bit to be at position 0.
例如:
0x40000000 => 30,因为0x40000000 >> 30 = 1
768 = 512 + 256 => 8
ex:
0x40000000 => 30 because 0x40000000 >> 30 = 1
768 = 512+256 => 8
这有效
if (Math.log2(x) == 31)
return 31;
if (Math.log2(x) > 31)
x = x & 0x7FFFFFFF;
return Math.log2(x & -x)
在javascript中,有没有更有效或更优雅的方法(内置?)?
Is there any more efficient or elegant way (builtin ?) to do this in javascript ?
推荐答案
您无法通过内置函数立即获得该结果,但是可以避免使用Math.log2
.有一个鲜为人知的函数Math.clz32
,该函数在其32位二进制表示形式中对数字的前导零进行计数.像这样使用它:
You cannot get that result immediately with a builtin function, but you can avoid using Math.log2
. There is a little known function Math.clz32
, which counts the number of leading zeroes of a number in its 32-bit binary representation. Use it like this:
function countTrailingZeroes(n) {
n |= 0; // Turn to 32 bit range
return n ? 31 - Math.clz32(n & -n) : 0;
}
console.log(countTrailingZeroes(0b11100)); // 2
三元表达式在那里捕获值 n = 0,就像简并的情况:它没有1位.
The ternary expression is there to catch the value n=0, which is like a degenerate case: it has no 1-bit.
这篇关于在javascript中获取数字的最低有效位的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!