Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the position instead of the value of the highest one bit in integer [duplicate]

Tags:

java

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

like image 987
manabreak Avatar asked Oct 28 '22 22:10

manabreak


2 Answers

Just combine it with numberOfTrailingZeros:

int pos = Integer.numberOfTrailingZeros(Integer.highestOneBit(f))
like image 57
xs0 Avatar answered Nov 15 '22 05:11

xs0


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
like image 27
Sweeper Avatar answered Nov 15 '22 06:11

Sweeper