Count And Rotate Bits With math/bits

Count set bits, measure leading and trailing zeros, rotate, and reverse bytes with the math/bits intrinsics instead of hand-rolled loops.

GoData Integrity

Code

gosnippet
23 lines
package main

import (
	"fmt"
	"math/bits"
)

func main() {
	var x uint8 = 0b10110100

	// 计 1 位数与前后导零:硬件指令语义,一行到位
	fmt.Println("ones:", bits.OnesCount8(x))
	fmt.Println("leading:", bits.LeadingZeros8(x), "trailing:", bits.TrailingZeros8(x))

	// 循环移位:移出的位从另一侧进入
	fmt.Println("rotl2:", bits.RotateLeft8(x, 2))

	// 位反转:整个字节镜像
	fmt.Println("reverse:", bits.Reverse8(x))

	// 有效位宽:最高位 1 的位置
	fmt.Println("len:", bits.Len8(x))
}

How the file behaves

Count the function main as the entire surface area of Count And Rotate Bits With math/bits.

Using it

The demo output is labeled (ones:, leading:, rotl2:), so the printed output reads as a trace of the operations performed.

Key statements

var x uint8 = 0b10110100

Interactive Tools for This Topic

FAQ

What does Count And Rotate Bits With math/bits print when run?
Execute the whole file; each printed line is prefixed with a label like `ones:`, `leading:`, `rotl2:`.