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 ?

v1nce
  • 735
  • 9
  • 20
  • 1
    Your title has a different question than your last sentence. You have answered the question in the title yourself. The answer to the final question is: No – trincot Apr 26 '20 at 14:13
  • First version just contained a raw code that did the job but only for positive numbers. Before scratching my head too much I was asking if I was on the wrong way. Now I have modified title and content accordingly (at least i hope so) – v1nce Apr 26 '20 at 17:05

1 Answers1

2

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.

trincot
  • 317,000
  • 35
  • 244
  • 286