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 t
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.
private static int mostSignificantBit(int myInt){
int i = 0;
while (myInt != 0) {
++i;
myInt >>>= 1;
}
return i;
}
Another way is calculate it mathematically:
private static int mostSignificantBit(int myInt){
if (myInt == 0) return 0; // special handling for 0
if (myInt < 0) return 32; // special handling for -ve
return (int)(Math.log(myInt)/Math.log(2)) +1;
}