std::popcount

Header: <bit>

Returns the number of 1 bits in the value of x.

# Declarations

template< class T >
constexpr int popcount( T x ) noexcept;

(since C++20)

# Parameters

# Return value

The number of 1 bits in the value of x.

# Notes

The name popcount is a contraction for “population count”.

# Example

#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
 
static_assert(std::popcount(0xFULL) == 4);
 
int main()
{
    for (const std::uint8_t x : {0, 0b00011101, 0b11111111})
        std::cout << "popcount( " << std::bitset<8>(x) << " ) = "
                  << std::popcount(x) << '\n';
}

# See also