Go 语言提供了对位的内置支持,以在位包的帮助下为预先声明的无符号整数类型实现位计数和操作功能。该包提供了OnesCount64()函数,用于查找 a 中的一位数。要访问 OnesCount64()函数,您需要借助 import 关键字在程序中添加一个math/bits包。
句法:
func OnesCount64(a uint64) int
参数:该函数接受一个 uint64 类型的参数,即 a。
返回值:此函数返回用于表示 a 的一位的总数。
示例 1:
// Golang program to illustrate bits.OnesCount64() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Using OnesCount64() function
a := bits.OnesCount64(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.OnesCount64() Function
package main
import (
"fmt"
"math/bits"
)
// Main function
func main() {
// Using OnesCount64() function
a1 := bits.OnesCount64(23)
fmt.Printf("OnesCount64(%064b) := %d\n", 23, a1)
a2 := bits.OnesCount64(13)
fmt.Printf("OnesCount64(%064b) := %d\n", 13, a2)
}
输出:
OnesCount64(0000000000000000000000000000000000000000000000000000000000010111) := 4
OnesCount64(0000000000000000000000000000000000000000000000000000000000001101) := 3