std::has_single_bit
来自cppreference.com
<tbody>
</tbody>
| 在标头 <bit> 定义
|
||
template< class T > constexpr bool has_single_bit( T x ) noexcept; |
(C++20 起) | |
检查 x 是否为二的整数次幂。
此重载只有在 T 为无符号整数类型(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned 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> 的公开成员函数)
|