Scroll to navigation

std::has_single_bit(3) C++ Standard Libary std::has_single_bit(3)

NAME

std::has_single_bit - std::has_single_bit

Synopsis


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


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-test 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

// Run this code


#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


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

2022.07.31 http://cppreference.com