What's the most efficient way of getting position of least significant bit of a number in javascript?

岁酱吖の 提交于 2020-06-17 04:56:31

问题


I got some numbers and I need to get how much they should be shifted for their lower bit to be at position 0.

ex:
0x40000000 => 30 because 0x40000000 >> 30 = 1
768 = 512+256 => 8

This works

if (Math.log2(x) == 31)
  return 31;
if (Math.log2(x) > 31)
  x = x & 0x7FFFFFFF;
return Math.log2(x & -x)

Is there any more efficient or elegant way (builtin ?) to do this in javascript ?


回答1:


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

The ternary expression is there to catch the value n=0, which is like a degenerate case: it has no 1-bit.



来源:https://stackoverflow.com/questions/61442006/whats-the-most-efficient-way-of-getting-position-of-least-significant-bit-of-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!