Namespaces
Variants

std::has_single_bit

来自 zh.cppreference.net
 
 
 
位操作
(C++20)
(C++23)
2 的整数次幂2
(C++20)
(C++20)
(C++20)
移位
(C++29)
(C++29)
循环移位
(C++20)
(C++20)
计数
(C++20)
(C++20)
(C++20)
排列
(C++29)
(C++29)
字节序
(C++20)
 
定义于头文件 <bit>
template< class T >
constexpr bool has_single_bit( T x ) noexcept;
(自 C++20 起)

检查 x 是否为 2 的整数次幂。

此重载仅在 T 是无符号整数类型(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或扩展的无符号整数类型)时参与重载决议。

参数

x - 无符号整数类型的值

返回值

如果 x 是2的整数次幂,则为 true ;否则为 false 。

注释

在 P1956R1 之前,此函数模板的提议名称为 ispow2 。

功能测试 宏 值 标准 功能
__cpp_lib_int_pow2 202002L (C++20) 整型二次幂 2 运算

可能的实现

template<typename T, typename ... U>
concept neither = (!std::same_as<T, U> && ...);
template<typename T>
concept strict_unsigned_integral = std::unsigned_integral<T> &&
    neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>;
// 第一版本
constexpr bool has_single_bit(strict_unsigned_integral auto x) noexcept
{
    return x && !(x & (x - 1));
}
// 第二版本
constexpr bool has_single_bit(strict_unsigned_integral auto x) noexcept
{
    return std::popcount(x) == 1;
}

示例

#include <bit>
#include <bitset>
#include <cmath>
#include <iostream>
int main()
{
    for (auto u{0u}; u != 0B1010; ++u)
    {
        std::cout << "u = " << u << " = " << std::bitset<4>(u);
        if (std::has_single_bit(u))
            std::cout << " = 2^" << std::log2(u) << " (is power of two)";
        std::cout << '\n';
    }
}

输出:

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

参见

(C++20)
统计无符号整数中 1 位的数量
(函数模板)
返回被设置为 true 的位的数量
( std::bitset<N> 的公开成员函数)
访问特定位
( std::bitset<N> 的公开成员函数)