How do I get the position, rather than the value, of the highest one bit in integer? I know I can get the value like this:
// Prints 8; in 1101, the highest bit is the one denoting 8
int f = 13;
System.out.println("Highest: " + Integer.highestOneBit(f));
However, I'd like to get position of the highest one bit - in this case, it would be 4 (since 1000
in binary == 8
, the highest one bit is the fourth one).
Just combine it with numberOfTrailingZeros:
int pos = Integer.numberOfTrailingZeros(Integer.highestOneBit(f))
Well, we can do this mathematically.
We basically want to get 4 from 8, 3 from 4, 2 from 2, 1 from 1, etc.
That is basically doing a log2 on the number and adding 1 to it. There is no log2
function in the java.lang.Math
class, but as you may know:
logx(y) = log10(y) / log10(x)
so we can just do this!
(Math.log10(Integer.highestOneBit(f)) / Math.log10(2)) + 1
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