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>
constexpr bool has_single_bit(T x) noexcept
{
    return x != 0 && (x & (x - 1)) == 0;
}

[edit] Example

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

Output:

has_single_bit(0) = false
has_single_bit(1) = true
has_single_bit(2) = true
has_single_bit(3) = false
has_single_bit(4) = true
has_single_bit(5) = false
has_single_bit(6) = false
has_single_bit(7) = false
has_single_bit(8) = true
has_single_bit(9) = false