# golang 统计uint64 数字二进制存储中1的数量

barfoo · · 865 次点击 · · 开始浏览

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))
}

1 回复  |  直到 2018-07-24 11:38:13

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

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))
}