If you insist on using bitwise operators directly, you can try something like this:
private int mostSignificantBit(int myInt){ int mask = 1 << 31; for(int bitIndex = 31; bitIndex >= 0; bitIndex--){ if((myInt & mask) != 0){ return bitIndex; } mask >>>= 1; } return -1; }
We initialize the mask 1 << 31 , because it represents 1, followed by 31 0. We use this value to check if index 31 (32nd place) is 1. When we and this value with myInt , we get 0 if the corresponding bit is not set to myInt . If so, we return that bitIndex . If not, we will move the mask to the right by 1 and try again. We repeat until we work out the place for the change, in which case this means that none of the bits have been set (perhaps you want to throw an exception here instead of returning -1).
Note that this will return a value of 0 for 1 and 6 for 64 ( 1000000 in binary format). You can customize this if you want. Note also that I used the unsigned operator on the right, and not the signed shift to the right. This is because the goal here is to process the source bits and not their signed interpretation, but in this case it does not matter, since all negative values end in the first iteration of the loop before the transition occurs.
source share