首页 > 其他 > 详细

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

时间:2018-07-15 18:28:09      阅读:262      评论:0      收藏:0      [点我收藏+]

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的数量

原文:https://www.cnblogs.com/barfoo/p/9314064.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!