/**
* 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 Unsigned 32-bit integer to examine.
* @returns The zero-based MSB position, or -1 if no bits are set.
* @throws RangeError if the value is not a valid unsigned 32-bit integer.
*/
function getMsbPosition(value: number): number {
if (
!Number.isInteger(value) ||
value < 0 ||
value > 0xFFFFFFFF
) {
throw new RangeError(
"Value must be an unsigned 32-bit integer."
);
}
if (value === 0) {
return -1;
}
// Math.clz32() returns the number of leading zero bits
// in the unsigned 32-bit representation.
return 31 - Math.clz32(value);
}
/**
* Application entry point.
*/
function main(): void {
const testValues: number[] = [
0,
1,
2,
8,
15,
0x1234,
0x80000000
];
for (const value of testValues) {
const msbPosition: number = getMsbPosition(value);
if (msbPosition >= 0) {
console.log(
`Value: ${value}, MSB position: ${msbPosition}`
);
} else {
console.log(
`Value: ${value}, no bits are set`
);
}
}
}
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
*/