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 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).

Contents

[edit] Return value

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

[edit] 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; 
}

[edit] 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

[edit] See also

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