std::has_single_bit

来自cppreference.com
< cpp‎ | numeric
 
 
 
位操纵
(C++20)
(C++23)
二的整数次幂
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 是否为二的整数次幂。

此重载只有在 T 为无符号整数类型(即 unsigned charunsigned shortunsigned intunsigned longunsigned long long 或扩展无符号整数类型)时才会参与重载决议。

目录

[编辑] 参数

x - 无符号整数类型的值

[编辑] 返回值

x 为二的整数次幂则为 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) << " (为二的幂)";
        std::cout << '\n';
    }
}

输出:

u = 0 = 0000
u = 1 = 0001 = 2^0 (为二的幂)
u = 2 = 0010 = 2^1 (为二的幂)
u = 3 = 0011
u = 4 = 0100 = 2^2 (为二的幂)
u = 5 = 0101
u = 6 = 0110
u = 7 = 0111
u = 8 = 1000 = 2^3 (为二的幂)
u = 9 = 1001

[编辑] 参阅

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