Namespaces
Variants

std:: has_single_bit

From cppreference.net
Utilities library
헤더 파일에 정의됨 <bit>
template < class T >
constexpr bool has_single_bit ( T x ) noexcept ;
(C++20부터)

x 가 2의 정수 거듭제곱인지 확인합니다.

이 오버로드는 다음 조건에서만 오버로드 해결에 참여합니다: T 가 부호 없는 정수 타입인 경우 (즉, unsigned char , unsigned short , unsigned int , unsigned long , unsigned long long , 또는 확장 부호 없는 정수 타입).

목차

매개변수

x - 부호 없는 정수형의 값

반환값

true 만약 x 가 2의 정수 거듭제곱인 경우; 그렇지 않으면 false .

참고 사항

P1956R1 이전에는, 이 함수 템플릿의 제안된 이름이 ispow2 이었습니다.

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

가능한 구현

template<typename T, typename ... U>
concept neither = (!std::same_as<T, U> && ...);
template<typename T>
concept strict_unsigned_integral = std::unsigned_integral<T> &&
    neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>;
// 첫 번째 버전
constexpr bool has_single_bit(strict_unsigned_integral auto x) noexcept
{
    return x && !(x & (x - 1));
}
// 두 번째 버전
constexpr bool has_single_bit(strict_unsigned_integral auto x) noexcept
{
    return std::popcount(x) == 1;
}

예제

#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

참고 항목

(C++20)
부호 없는 정수에서 1 비트의 개수를 셉니다
(함수 템플릿)
true 로 설정된 비트의 개수를 반환합니다
( std::bitset<N> 의 public 멤버 함수)
특정 비트에 접근합니다
( std::bitset<N> 의 public 멤버 함수)