Why it matters

Popcount powers bitmap indexes, Hamming distance, and rank/select. Understanding options shapes throughput.

Advertisement

The architecture

Naive loop; Kernighan; SWAR parallel bit-count; hardware POPCNT.

Hardware wins by 5-20x on wide integers.

Popcount algorithmsNaive / Kernighanloop over bitsSWARparallel bit addPOPCNTsingle CPU instructionGCC __builtin_popcountll maps to POPCNT when available; portable and fast
Popcount algorithms.
Advertisement

How it works end to end

__builtin_popcountll on GCC/Clang.

POPCNT on x86-64 v2+.

NEON CNT on ARM.