Java - How to get the bit number (index) from a given value?

Viewed 147

I have one single number which is a guaranteed power of two (1,2,4,8,16,...etc). How can I get the "bit index" from this number?

Say, I get the number "8" -> The answer I seek is "3" (bit#3)

 1 -> 0
 2 -> 1
 4 -> 2
 8 -> 3
16 -> 4
32 -> 5
..etc...

Of course I can build an array or a dictionary (the key being the number, the value the bit#) of... say 16 indices to get from the value to the bit#,

I can also do a

int i = 0, counter = 1;
while (counter != needed_value) {
    counter *= 2;
    i++;
}
// now "i" contains my bit#

but is there a... more fancy way?

4 Answers

Nothing fancy, just what the java.lang.Integer class provides (although the implementation is somewhat fancy):

int lowestOneBit = Integer.numberOfTrailingZeros(needed_value);

When 2^x = y then log2(y) = x. You know y, so the solution is:

Math.log(y) / Math.log(2)

This is because logb(a) = log(a) / log(b).

You can just find first significant bit in integer:

public static Optional<Integer> getFirstSignificantBit(int src) {
    for (int i = 0; i < 32; i++) {
        if ((src & 1) == 1) {
            return Optional.of(i);
        }
        src >>= 1;
    }

    return Optional.empty();
}

How about recursive!

  private static int bitIndex(int n) {
        if (n <= 1)
            return 0;
        return 1 + bitIndex(n/2);
    }
Related