Is there bitwise solution to find the index of first set bit in mask with only one bit set? e.g. for 8 it would be 3, for 16 => 4 and so on. No loops plz. The best solution I can come up with is to createa map of bit to index.
Set bits are checked from the binary representation of the number. The indexing in binary representation starts from index 0 from the right direction and propagates towards left. Example − in the binary number '011101', at index 0 from right we have 1, at index 1 from right we have 0, and so on.
Finding the lowest set bit turns out to be surprisingly easy, with the right combination of bitwise and arithmetic operators. Suppose we wish to find the lowest set bit of x (which is known to be non-zero). If we subtract 1 from x then this bit is cleared, but all the other one bits in x remain set.
In a binary number, the bit furthest to the left is called the most significant bit (msb) and the bit furthest to the right is called the least significant bit (lsb). The MSB gives the sign of the number (sign bit) , 0 for positive and 1 for negative.
function firstBit(x) {
return Math.floor(
Math.log(x | 0) / Math.log(2)
) + 1;
}
i=4; console.log(i.toString(2), firstBit(i)); // 100 3
i=7; console.log(i.toString(2), firstBit(i)); // 111 3
i=8; console.log(i.toString(2), firstBit(i)); // 1000 4
For posterity, ES6 introduced Math.log2
(and also log10
) which does exactly that:
Math.log2(8) === 3
As a reminder, logA(x)
is logB(x) / logB(A)
for any A
and B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With