"""
Demonstrates how to find the position of the most significant set bit (MSB)
of an unsigned integer.
"""
def get_msb_position(value: int) -> int:
"""
Return the zero-based position of the most significant set bit (MSB).
Examples:
1 -> 0
2 -> 1
8 -> 3
15 -> 3
Args:
value: A non-negative integer.
Returns:
The zero-based position of the highest set bit.
Raises:
ValueError: If value is negative.
"""
if value < 0:
raise ValueError("value must be a non-negative integer")
if value == 0:
return -1
return value.bit_length() - 1
def main() -> None:
"""Program entry point."""
test_values = (
0,
1,
2,
8,
15,
0x1234,
0x80000000,
)
for value in test_values:
position = get_msb_position(value)
if position >= 0:
print(f"Value: {value}, MSB position: {position}")
else:
print(f"Value: {value}, no bits are set")
if __name__ == "__main__":
main()
'''
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
'''