package main
import (
"fmt"
)
// pc[i] is the population count of i.
var pc [256]byte
func init() {
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
}
}
func PopCount(x uint64) int {
return int(pc[byte(x>>(0*8))] +
pc[byte(x>>(1*8))] +
pc[byte(x>>(2*8))] +
pc[byte(x>>(3*8))] +
pc[byte(x>>(4*8))] +
pc[byte(x>>(5*8))] +
pc[byte(x>>(6*8))] +
pc[byte(x>>(7*8))])
}
func AnalyzePopCount(x uint64) int {
count := 0
var i uint
for i = 0; i < 8; i++ {
tmpNum := x >> (i * 8)
fmt.Printf("tmpNum:\n%v\n%x\n%b\n\n", tmpNum, tmpNum, tmpNum)
byteNum := byte(tmpNum)
fmt.Printf("byteNum:\n%v\n%x\n%b\ncount:%d\n\n", byteNum, byteNum, byteNum, pc[byteNum])
count += int(pc[byteNum])
}
return count
}
func main() {
/*
fmt.Println(2 << 1)
fmt.Println(2<<1 + 1)
fmt.Println(4 >> 1)
*/
fmt.Println(pc[255])
for i := range pc {
fmt.Printf("%v, ", pc[i])
if (i % 16) == 15 {
fmt.Println()
}
}
pc[0] = 255
fmt.Println(pc[0])
pc[0] = 254
fmt.Println(pc[0])
//fmt.Printf("\n\n\n\n\n")
//fmt.Println(PopCount(23495631783903473))
//fmt.Println(AnalyzePopCount(23495631783903473))
}
golang 统计uint64 数字二进制存储中1的数量
barfoo ·package main
import (
"fmt"
)
// pc[i] is the population count of i.
var pc [256]byte
func init() {
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
}
}
func PopCount(x uint64) int {
return int(pc[byte(x>>(0*8))] +
pc[byte(x>>(1*8))] +
pc[byte(x>>(2*8))] +
pc[byte(x>>(3*8))] +
pc[byte(x>>(4*8))] +
pc[byte(x>>(5*8))] +
pc[byte(x>>(6*8))] +
pc[byte(x>>(7*8))])
}
func AnalyzePopCount(x uint64) int {
count := 0
var i uint
for i = 0; i < 8; i++ {
tmpNum := x >> (i * 8)
fmt.Printf("tmpNum:\n%v\n%x\n%b\n\n", tmpNum, tmpNum, tmpNum)
byteNum := byte(tmpNum)
fmt.Printf("byteNum:\n%v\n%x\n%b\ncount:%d\n\n", byteNum, byteNum, byteNum, pc[byteNum])
count += int(pc[byteNum])
}
return count
}
func main() {
/*
fmt.Println(2 << 1)
fmt.Println(2<<1 + 1)
fmt.Println(4 >> 1)
*/
fmt.Println(pc[255])
for i := range pc {
fmt.Printf("%v, ", pc[i])
if (i % 16) == 15 {
fmt.Println()
}
}
pc[0] = 255
fmt.Println(pc[0])
pc[0] = 254
fmt.Println(pc[0])
//fmt.Printf("\n\n\n\n\n")
//fmt.Println(PopCount(23495631783903473))
//fmt.Println(AnalyzePopCount(23495631783903473))
}