Reverse bit shift to the left in the format 1 << n

Let's say I have the following bit masks:

1 << 1, // 2
1 << 2, // 4 
1 << 3, // 8 
1 << 4, // 16 
1 << 5, // 32 
1 << 6  // 64

I would like to get a "reverse".

This task:

void foo(int n) {
  int c = 1;
  while (n/2 >= 2) {
    n /= 2;  
    c++;;
  }
  println(c);
}

For example, it 1 << 4led to 16. If I started foo(16), it prints 4. However, I feel that it can be done much easier, but I can’t figure out how to do it.

Is it possible?

+4
source share
3 answers

BigIntegerhas many useful methods - including getLowestSetBit () . He probably does it as fast as possible.

public void test() {
    System.out.println(BigInteger.valueOf(16).getLowestSetBit());
}
+2
source
void foo(int n)
{
    println( (Math.log(n) / Math.log(2))); 
    //cast to int with (int) to take off decimal place
}

Returns the "reverse" bit shift when you call it, the base 2 logarithm.

+1

.

private static int foo2(int value) {
    int result = 0;

    int mask = 0xFFFF;
    int shift = 1<<4;
    for (int j = 0; j < 5; j++) {
        result <<= 1;
        if ((value & mask) == 0) {
            result |= 1;
            value >>>= shift;
        }
        shift >>>= 1;
        mask >>= shift;
    }
    return result;
}
+1

Source: https://habr.com/ru/post/1599355/


All Articles