std::has_single_bit(3)
β¨ std::has_single_bit(3) β¨
okay so this is the C++ Standard Libary manual page for std::has_single_bit, and it is lowkey giving bit-nerd main character energy π
. We are checking whether a number is an integral power of two, and the vibe check is immaculate. no cap.
πΈ NAME πΈ
std::has_single_bit β std::has_single_bit (yes bestie, that is the whole name, iconic minimalism π)
β¨ 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Β· Value:202002LΒ· Std:(C++20)Β· Feature: Integral power-of-2 operations
π 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 && !(x & (x - 1));
}
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 <cmath>
#include <iostream>
int main()
{
for (auto u = 0u; u != 10; ++u)
{
std::cout << "u = " << u << " = " << std::bitset<4>(u);
if (std::has_single_bit(u)) // `ispow2` before P1956R1
std::cout << " = 2^" << std::log2(u) << " (is power of two)";
std::cout << '\n';
}
}
πΈ Output: πΈ
u = 0 = 0000
u = 1 = 0001 = 2^0 (is power of two)
u = 2 = 0010 = 2^1 (is power of two)
u = 3 = 0011
u = 4 = 0100 = 2^2 (is power of two)
u = 5 = 0101
u = 6 = 0110
u = 7 = 0111
u = 8 = 1000 = 2^3 (is power of two)
u = 9 = 1001
π See also π
popcountβ counts the number of 1 bits in an unsigned integer(C++20)(function template)countβ returns the number of bits set totrue(public member function of std::bitset<N>)testβ accesses specific bit(public member function of std::bitset<N>)
that's a wrap, bestie! source/version: http://cppreference.com Β· date: 2024.06.10 Β· page: std::has_single_bit(3) πβ¨ periodt.
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms