Golang bits.OnesCount16() 函数及示例
Go 语言提供了内置支持来通过 bits 包实现对预定义无符号整型的位计数和操作函数。该包提供了 OnesCount16() 函数 ,用于查找 a 中一位的数量。要访问 OnesCount16() 函数,您需要使用 import 关键字在程序中添加 math/bits 包。
语法:
func OnesCount16(a uint16) int
参数: 此函数使用 uint16 类型的一个参数 a。
返回值: 此函数返回用于表示 a 的所有一位的总数。
示例 1:
// Golang program to illustrate bits.OnesCount16() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Using OnesCount16() function
a := bits.OnesCount16(5)
fmt.Printf("用于表示 %d 的所有一位的总数为: %d", 5, a)
}
输出:
用于表示 5 的所有一位的总数为: 2
示例 2:
// Golang program to illustrate bits.OnesCount16() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Using OnesCount16() function
a1 := bits.OnesCount16(4)
fmt.Printf("OnesCount16(%016b) := %d\n", 4, a1)
a2 := bits.OnesCount16(13)
fmt.Printf("OnesCount16(%016b) := %d\n", 13, a2)
}
输出:
OnesCount16(0000000000000100) := 1
OnesCount16(0000000000001101) := 3
极客教程