Logo

Programming-Idioms

  • Python
  • Go
import "math/bits"
c := bits.OnesCount(i)

i is a uint.
All OnesCountX functions take unsigned integer types.
func PopCountUInt64(i uint64) (c int) {
	i -= (i >> 1) & 0x5555555555555555
	i = (i>>2)&0x3333333333333333 + i&0x3333333333333333
	i += i >> 4
	i &= 0x0f0f0f0f0f0f0f0f
	i *= 0x0101010101010101
	return int(i >> 56)
}

func PopCountUInt32(i uint32) (n int) {
	i -= (i >> 1) & 0x55555555
	i = (i>>2)&0x33333333 + i&0x33333333
	i += i >> 4
	i &= 0x0f0f0f0f
	i *= 0x01010101
	return int(i >> 24)
}

This was useful only before go 1.9.
See math/bits.OnesCount instead.
c = bin(i).count("1")
c = i.bit_count()

For Python 3.10+
#include <stdint.h>
uint32_t c = i;
c = (c & 0x55555555) + ((c & 0xAAAAAAAA) >> 1);
c = (c & 0x33333333) + ((c & 0xCCCCCCCC) >> 2);
c = (c & 0x0F0F0F0F) + ((c & 0xF0F0F0F0) >> 4);
c = (c & 0x00FF00FF) + ((c & 0xFF00FF00) >> 8);
c = (c & 0x0000FFFF) + ((c & 0xFFFF0000) >> 16);

add even and odd bits
then add even and odd pairs of bits
then add even and odd quadruples of bits
then add even and odd octets of bits
then add whatever groups of 16 bits are called
done

with gcc you can also use the function _builtin_popcount

New implementation...
< >
deleplace