/**
* Demonstrates how to find the position of the most significant set bit (MSB)
* in an unsigned 32-bit integer.
*/
public final class MostSignificantBitDemo {
private MostSignificantBitDemo() {
// Prevent instantiation of utility class.
}
/**
* Returns the zero-based position of the most significant set bit (MSB)
* in an unsigned 32-bit integer.
*
* Examples:
* 1 -> 0
* 2 -> 1
* 8 -> 3
* 15 -> 3
*
* @param value the unsigned 32-bit value stored in an int
* @return the zero-based MSB position, or -1 if value is 0
*/
public static int msbPosition(int value) {
if (value == 0) {
return -1;
}
// Integer.SIZE is 32.
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(value);
}
public static void main(String[] args) {
int[] testValues = {
0,
1,
2,
8,
15,
0x1234,
0x80000000
};
for (int value : testValues) {
int position = msbPosition(value);
if (position >= 0) {
System.out.printf(
"Value: %s, MSB position: %d%n",
Integer.toUnsignedString(value),
position
);
} else {
System.out.printf(
"Value: %s, no bits are set%n",
Integer.toUnsignedString(value)
);
}
}
}
}
/*
run:
Value: 0, no bits are set
Value: 1, MSB position: 0
Value: 2, MSB position: 1
Value: 8, MSB position: 3
Value: 15, MSB position: 3
Value: 4660, MSB position: 12
Value: 2147483648, MSB position: 31
*/