cpp / latest / numeric / has_single_bit.html /

std::has_single_bit

Defined in header <bit>
template< class T >
constexpr bool has_single_bit( T x ) noexcept;
(since C++20)

Checks if x is an integral power of two.

This overload participates in overload resolution only if T is an unsigned integer type (that is, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, or an extended unsigned integer type).

Parameters

x - value of unsigned integer type

Return value

true if x is an integral power of two; otherwise false.

Notes

Feature testing macro: __cpp_lib_int_pow2.

Possible implementation

First version
template <std::unsigned_integral T>
    requires !std::same_as<T, bool> && !std::same_as<T, char> &&
             !std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
             !std::same_as<T, char32_t> && !std::same_as<T, wchar_t> 
constexpr bool has_single_bit(T x) noexcept
{
    return x != 0 && (x & (x - 1)) == 0;
}
Second version
template <std::unsigned_integral T>
    requires !std::same_as<T, bool> && !std::same_as<T, char> &&
             !std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
             !std::same_as<T, char32_t> && !std::same_as<T, wchar_t> 
constexpr bool has_single_bit(T x) noexcept
{
    return std::popcount(x) == 1; 
}

Example

#include <bit>
#include <bitset>
#include <iostream>
 
int main()
{
    std::cout << std::boolalpha;
    for (auto i = 0u; i < 10u; ++i) {
        std::cout << "has_single_bit( " << std::bitset<4>(i) << " ) = "
                  << std::has_single_bit(i) // `ispow2` before P1956R1
                  << '\n';
    }
}

Output:

has_single_bit( 0000 ) = false
has_single_bit( 0001 ) = true
has_single_bit( 0010 ) = true
has_single_bit( 0011 ) = false
has_single_bit( 0100 ) = true
has_single_bit( 0101 ) = false
has_single_bit( 0110 ) = false
has_single_bit( 0111 ) = false
has_single_bit( 1000 ) = true
has_single_bit( 1001 ) = false

See also

(C++20)
counts the number of 1 bits in an unsigned integer
(function template)
returns the number of bits set to true
(public member function of std::bitset<N>)
accesses specific bit
(public member function of std::bitset<N>)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/numeric/has_single_bit