Golang statistics UInt64 number of 1 in binary storage

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.