std::bit_floor
来自 cppreference.cn
定义于头文件 <bit> |
||
template< class T > constexpr T bit_floor( T x ) noexcept; |
(C++20 起) | |
如果 x 不为零,则计算不大于 x 的最大 2 的整数次幂。 如果 x 为零,则返回零。
此重载仅在 T
是无符号整数类型时参与重载决议(即,unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或扩展无符号整数类型)。
目录 |
[edit] 参数
x | - | 无符号整数值 |
[edit] 返回值
如果 x 为零则为零; 否则,为不大于 x 的最大 2 的整数次幂。
[edit] 注解
在 P1956R1 之前,此函数模板的提议名称为 floor2
。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_int_pow2 |
202002L |
(C++20) | 2 的整数次幂运算 |
[edit] 可能的实现
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 T bit_floor(T x) noexcept { if (x != 0) return T{1} << (std::bit_width(x) - 1); return 0; } |
[edit] 示例
运行此代码
#include <bit> #include <bitset> #include <iostream> int main() { using bin = std::bitset<8>; for (unsigned x{}; x != 012; ++x) std::cout << "bit_floor( " << bin(x) << " ) = " << bin(std::bit_floor(x)) << '\n'; }
输出
bit_floor( 00000000 ) = 00000000 bit_floor( 00000001 ) = 00000001 bit_floor( 00000010 ) = 00000010 bit_floor( 00000011 ) = 00000010 bit_floor( 00000100 ) = 00000100 bit_floor( 00000101 ) = 00000100 bit_floor( 00000110 ) = 00000100 bit_floor( 00000111 ) = 00000100 bit_floor( 00001000 ) = 00001000 bit_floor( 00001001 ) = 00001000
[edit] 参见
(C++20) |
查找不小于给定值的最小 2 的整数次幂 (函数模板) |
(C++20) |
计算按位右旋转的结果 (函数模板) |
(C++20) |
查找表示给定值所需的最小位数 (函数模板) |
(C++20) |
检查数字是否为 2 的整数次幂 (函数模板) |