How do you find the position of the most significant bit (MSB) of an unsigned integer in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"math/bits"
)

/*
GetMSBPosition 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

Returns:

	-1 if value is 0 (no bits are set).
*/
func GetMSBPosition(value uint32) int {
	if value == 0 {
		return -1
	}

	return bits.Len32(value) - 1
}

func main() {
	testValues := []uint32{
		0,
		1,
		2,
		8,
		15,
		0x1234,
		0x80000000,
	}

	for _, value := range testValues {
		position := GetMSBPosition(value)

		if position >= 0 {
			fmt.Printf(
				"Value: %d, MSB position: %d\n",
				value,
				position,
			)
		} else {
			fmt.Printf(
				"Value: %d, no bits are set\n",
				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

*/

 



answered Oct 1 by avibootz
...