Efficient Bit Manipulation in Go 1.9
Go 1.9, released in August 2017, introduced the maths/bits
package. This package provides optimized functions for bit counting and manipulation of unsigned integers. These are useful in low-level environments where the individual bits stored in an integer are of importance. Let’s take a look at some of the functions.
First up, Len
returns the minimum number of bits required to represent a value x
.
package main
import (
"fmt"
"math/bits"
)
func main() {
var a uint = 31
fmt.Printf("bits.Len(%d) = %d\n", a, bits.Len(a))
a++
fmt.Printf("bits.Len(%d) = %d\n", a, bits.Len(a))
}
Which outputs:
bits.Len(31) = 5
bits.Len(32) = 6
Playground link
This is because 31 is 11111
in binary, and 32 is 100000
. The first significant bit is in each case is in position 5 and 6, respectively, when counting positions from the right.
This also allows us to easily illustrate