2

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?

Grisgram
  • 3,105
  • 3
  • 25
  • 42

4 Answers4

3

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

int lowestOneBit = Integer.numberOfTrailingZeros(needed_value);
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
  • That looks good - Thank you very much - wasn't aware of this! and yes... looking at the implementation ... whow :) – Grisgram May 08 '20 at 06:24
  • @Grisgram the `Integer` class has several such helpful gems - look at `highestOneBit()`, `lowestOneBit()`, `bitCount()`, `reverse()`, `reverseBytes()` – Thomas Kläger May 08 '20 at 06:47
  • Thanks - yes I see - there are interesting things (reverseBytes!) that can help greatly – Grisgram May 08 '20 at 11:09
3

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).

akuzminykh
  • 4,522
  • 4
  • 15
  • 36
0

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();
}
0

How about recursive!

  private static int bitIndex(int n) {
        if (n <= 1)
            return 0;
        return 1 + bitIndex(n/2);
    }
Peter Wang
  • 104
  • 4