numeric_has_single_bit

numeric_has_single_bit (2의 거듭제곱인지 확인)

std::has_single_bit은 x가 2의 정수 거듭제곱인지 확인하는 함수예요. C++20부터 사용할 수 있어요.

출처: cppreference

본문

<bit> 헤더에 정의되어 있고, 시그니처는 다음과 같아요.

template< class T >
constexpr bool has_single_bit( T x ) noexcept;

(since C++20)

x가 2의 정수 거듭제곱인지 검사해요.

매개변수 (Parameters)

  • x — 검사할 값

타입 요구사항 (Type requirements)

  • T — 오버로드 해석에 참여하려면 부호 없는 정수 타입이어야 해요.

반환값 (Return value)

x가 2의 정수 거듭제곱이면 true, 그 외에는 false예요.

참고 (Notes)

P1956R1 이전에는 이 함수 템플릿의 제안된 이름이 ispow2였어요.

피처 테스트 매크로 표준 기능
__cpp_lib_int_pow2 202002L (C++20) 정수 2의 거듭제곱 연산

가능한 구현 (Possible implementation)

template<typename T, typename ... U>
concept neither = (!std::same_as<T, U> && ...);

template<std::unsigned_integral T>
    requires neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>
constexpr bool has_single_bit(T x) noexcept
{
    return std::popcount(x) == 1;
}

예제 (Example)

이 코드를 실행해 봐요.

#include <bit>
#include <bitset>
#include <cmath>
#include <iostream>

int main()
{
    for (auto u{0u}; u != 0B1010; ++u)
    {
        std::cout << "u = " << u << " = " << std::bitset<4>(u);
        if (std::has_single_bit(u))
            std::cout << " = 2^" << std::log2(u) << " (is power of two)";
        std::cout << '\n';
    }
}

출력:

u = 0 = 0000
u = 1 = 0001 = 2^0 (is power of two)
u = 2 = 0010 = 2^1 (is power of two)
u = 3 = 0011
u = 4 = 0100 = 2^2 (is power of two)
u = 5 = 0101
u = 6 = 0110
u = 7 = 0111
u = 8 = 1000 = 2^3 (is power of two)
u = 9 = 1001

더 알아보기 (Learn more)

cppreference