github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bit/count.go (about)

     1  package bit
     2  
     3  const (
     4  	m1  = 0x5555555555555555 //binary: 0101...
     5  	m2  = 0x3333333333333333 //binary: 00110011..
     6  	m4  = 0x0f0f0f0f0f0f0f0f //binary:  4 zeros,  4 ones ...
     7  	m8  = 0x00ff00ff00ff00ff //binary:  8 zeros,  8 ones ...
     8  	m16 = 0x0000ffff0000ffff //binary: 16 zeros, 16 ones ...
     9  	m32 = 0x00000000ffffffff //binary: 32 zeros, 32 ones
    10  
    11  	b32  = 0xFFFFFFFF
    12  	ms1  = m1 & b32
    13  	ms2  = m2 & b32
    14  	ms4  = m4 & b32
    15  	ms8  = m8 & b32
    16  	ms16 = m16 & b32
    17  	ms32 = m32 & b32
    18  )
    19  
    20  func Count(x uint64) int {
    21  	x = (x & m1) + ((x >> 1) & m1)
    22  	x = (x & m2) + ((x >> 2) & m2)
    23  	x = (x & m4) + ((x >> 4) & m4)
    24  	x = (x & m8) + ((x >> 8) & m8)
    25  	x = (x & m16) + ((x >> 16) & m16)
    26  	x = (x & m32) + ((x >> 32) & m32)
    27  	return int(x)
    28  }