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

1

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 ?

javascript
bit-manipulation
bit
asked on Stack Overflow Apr 26, 2020 by v1nce • edited Apr 26, 2020 by v1nce

1 Answer

3

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.

answered on Stack Overflow Apr 26, 2020 by trincot • edited May 1, 2020 by trincot

User contributions licensed under CC BY-SA 3.0