命名空间
变体
操作

std::has_single_bit

来自 cppreference.cn
< cpp‎ | numeric
 
 
 
位操作
(C++20)
(C++23)
2 的整数次幂
has_single_bit
(C++20)
(C++20)
(C++20)
(C++20)
旋转
(C++20)
(C++20)
计数
(C++20)
(C++20)
(C++20)
字节序
(C++20)
 
定义于头文件 <bit>
template< class T >
constexpr bool has_single_bit( T x ) noexcept;
(C++20 起)

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

此重载仅在 T 是无符号整数类型时参与重载决议(即,unsigned charunsigned shortunsigned intunsigned longunsigned long long 或扩展无符号整数类型)。

内容

[编辑] 参数

x - 无符号整数类型的值

[编辑] 返回值

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

[编辑] 注解

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

特性测试 Std 特性
__cpp_lib_int_pow2 202002L (C++20) 整数二次幂运算

[编辑] 可能的实现

第一版
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));
}
第二版
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;
}

[编辑] 示例

#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> 的公共成员函数) [编辑]