numeric_popcount
numeric_popcount (1 비트 개수)
std::popcount는 x의 값에서 1 비트의 개수를 세는 함수예요. C++20부터 사용할 수 있어요.
출처: cppreference
본문
<bit> 헤더에 정의되어 있고, 시그니처는 다음과 같아요.
template< class T >
constexpr int popcount( T x ) noexcept;
(since C++20)
x의 값에서 1 비트의 개수를 반환해요.
매개변수 (Parameters)
- x — 비트를 셀 값
타입 요구사항 (Type requirements)
- T — 오버로드 해석에 참여하려면 부호 없는 정수 타입이어야 해요.
반환값 (Return value)
x의 값에서 1 비트의 개수예요.
참고 (Notes)
popcount라는 이름은 "population count"(인구수 세기)의 줄임말이에요.
| 피처 테스트 매크로 | 값 | 표준 | 기능 |
|---|---|---|---|
__cpp_lib_bitops |
201907L | (C++20) | 비트 연산 |
예제 (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';
}
출력:
popcount( 00000000 ) = 0
popcount( 00011101 ) = 4
popcount( 11111111 ) = 8