Home

builtinpopcount

Builtinpopcount refers to a set of compiler intrinsic functions that count the number of set bits (1s) in the binary representation of an unsigned integer. The operation is widely used in bit-twiddling, bitboard algorithms, and algorithms that rely on population counts for performance or simplicity. In practice, these intrinsics usually map to a single hardware instruction on modern CPUs, when such an instruction is available.

In GCC and Clang the common names are __builtin_popcount for unsigned int, __builtin_popcountl for unsigned long,

Other compilers provide similar functionality under different names. For example, Microsoft compilers expose a family of

Usage considerations include type width and portability. If you are counting bits in wider types, use the

and
__builtin_popcountll
for
unsigned
long
long.
The
return
type
is
int,
and
the
result
is
the
number
of
1
bits
in
the
input,
ranging
from
0
to
the
number
of
bits
in
the
input
type.
The
argument
is
treated
as
unsigned;
if
a
signed
type
is
supplied,
it
is
converted
to
unsigned
before
counting.
intrinsics
such
as
__popcnt
in
their
headers.
In
addition,
the
C++20
standard
library
offers
a
portable
alternative:
std::popcount
in
the
<bit>
header,
which
performs
the
same
operation
in
a
standard,
type-safe
way.
corresponding
built-in
variant
or
cast
to
the
appropriate
unsigned
type.
When
the
argument
is
a
constant,
many
compilers
can
evaluate
the
result
at
compile
time.
While
built-ins
offer
high
performance
on
supported
hardware,
portable
code
should
rely
on
standard
library
facilities
where
possible.