math/bits

Guided tour · Math · pkg.go.dev →

Low-level bit counting, shifting, leading/trailing zeros. Uses CPU instructions where available — very fast.

Counting

OnesCount, LeadingZeros, TrailingZeros

bits.OnesCount64(0b10110101)   // 5
bits.LeadingZeros8(1)          // 7
bits.TrailingZeros32(8)        // 3

Len — minimum bits needed to represent n

bits.Len(0)    // 0
bits.Len(1)    // 1
bits.Len(255)  // 8

Rotations and byte swap

RotateLeft, ReverseBytes

bits.RotateLeft32(1, 4)           // 16
bits.ReverseBytes32(0x11223344)   // 0x44332211

Math with overflow awareness

Add64, Sub64, Mul64, Div64 return carry/borrow/hi halves. Use when implementing big-int primitives or checksums.

128-bit multiply from two 64-bit values

hi, lo := bits.Mul64(math.MaxUint64, 2)
fmt.Println(hi, lo)