Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of first set bit

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.

like image 605
Denis Narushevich Avatar asked Aug 08 '13 19:08

Denis Narushevich


People also ask

How do you find the index of a set bit?

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.

How do you find the lowest set bit?

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.

How do I find MSB and LSB?

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.


2 Answers

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
like image 161
Paul S. Avatar answered Oct 01 '22 07:10

Paul S.


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

like image 37
floribon Avatar answered Oct 01 '22 07:10

floribon