Golang bits.OnesCount8()函数的用法及示例
Go语言提供了内置支持来实现位计数和操作函数的bits包,用于预声明的无符号整数类型。这个包提供了 OnesCount8()函数 ,用于查找一个数字中有几个1位。要访问OnesCount8()函数,您需要借助import关键字在程序中添加math/bits包。
语法:
func OnesCount8(a uint8) int
参数: 这个函数需要一个uint8类型的参数a。
返回值: 这个函数返回用于表示a的所有1位的总数。
示例1:
// Golang program to illustrate bits.OnesCount8() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Using OnesCount8() function
a := bits.OnesCount8(5)
fmt.Printf("Total number of one bits that"+
" are used to represent %d: %d", 5, a)
}
输出:
Total number of one bits that are used to represent 5: 2
示例2:
// Golang program to illustrate bits.OnesCount8() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Using OnesCount8() function
a1 := bits.OnesCount8(4)
fmt.Printf("OnesCount8(%08b) = %d\n", 4, a1)
a2 := bits.OnesCount8(13)
fmt.Printf("OnesCount8(%08b) = %d\n", 13, a2)
}
输出:
OnesCount8(00000100) = 1
OnesCount8(00001101) = 3
极客教程