Namespaces
Variants
Views
Actions

std::has_single_bit

From cppreference.com
< cpp‎ | numeric
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 only participates in overload resolution 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).

[edit] Return value

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

[edit] Possible implementation

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;
}

[edit] Example

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

Output:

has_single_bit(00000000) = false
has_single_bit(00000001) = true
has_single_bit(00000010) = true
has_single_bit(00000011) = false
has_single_bit(00000100) = true
has_single_bit(00000101) = false
has_single_bit(00000110) = false
has_single_bit(00000111) = false
has_single_bit(00001000) = true
has_single_bit(00001001) = false