I want to find the most significant bit that is set to 1
. I have tried every possible way from &
to ORing all of the bits from 1
to 31
and it doesn't work.
Like if 1000000
I would like to have 7
.
I want to find the most significant bit that is set to 1
. I have tried every possible way from &
to ORing all of the bits from 1
to 31
and it doesn't work.
Like if 1000000
I would like to have 7
.
The slickest implementation I've come across - three iterations and a table lookup.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#numberOfLeadingZeros%28int%29 You want something like
32 - Integer.numberOfLeadingZeros(value)
.Just to add another approach
For Little Endian format:
If you insist on directly using bitwise operators, you can try something like this:
We initialize the mask to
1 << 31
because that represents a 1 followed by 31 0's. We use that value to test if index 31 (the 32nd spot) is a 1. When weand
this value withmyInt
, we get a 0 unless the corresponding bit is set inmyInt
. If this is the case, we return thatbitIndex
. If not, then we shift the mask to the right by 1 and try again. We repeat until we run out of places to shift, in which case it means none of the bits were set (maybe you want to throw an exception here instead of returning -1).Note that this will return the value
0
for1
and6
for64
(1000000
in binary). You can adjust that if you prefer. Note also that I used the unsigned right operator rather than the signed right shift. This is because the intent here is to deal with raw bits rather than their signed interpretation, but it doesn't matter in this instance since all negative values will terminate in the first iteration of the loop before shifting occurs.Though there is an answer accepted, I have another ways to share which I think is easier.
If you want to use bitwise operations, here is the way. Basically, I am right-shifting the integer until it become zero. No mask is required.
Another way is calculate it mathematically: