Java – set the most important bit by bit
I want to find the most important bit set to 1 I've tried all possible ways from & oring all bits from 1 to 31, it doesn't work
Like 1000000, I want to have 7
Solution
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 to 1 < < 31 because it represents 1 and then 31 0 We use this value to test whether index 31 (point 32) is 1 When we use this value with Myint, we get 0 unless the corresponding bit is set in Myint If this is the case, we return bitindex If not, then we move the mask 1 to the right and try again We repeat until we run out of places to shift. In this case, it means that no bits are set (maybe you want to throw an exception here instead of returning - 1) Note that this will return values 0 of 1 and 6 of 64 (binary 1000000) You can adjust it if you like Also note that I use the unsigned right operator instead of the signed right shift operator This is because the intention here is to deal with the original bits rather than their signed interpretation, but it does not matter in this case, because all negative values will terminate in the first iteration of the loop before the conversion occurs