std::bit_floor
来自cppreference.com
在标头 <bit> 定义
|
||
template< class T > constexpr T bit_floor( T x ) noexcept; |
(C++20 起) | |
若 x 非零,则计算不大于 x 的最大的二的整数次幂。若 x 为零,则返回零。
此重载只有在 T
为无符号整数类型(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或扩展无符号整数类型)时才会参与重载决议。
参数
x | - | 无符号整数值 |
返回值
若 x 为零则为零;否则为不大于 x 的最大的二的整数次幂。
注解
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__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 T bit_floor(T x) noexcept { if (x != 0) return T{1} << (std::bit_width(x) - 1); return 0; } |
示例
运行此代码
#include <bit> #include <bitset> #include <iostream> int main() { using bin = std::bitset<8>; for (unsigned x = 0; x != 10; ++x) { auto const z = std::bit_floor(x); // P1956R1 前为 `floor2` std::cout << "bit_floor( " << bin(x) << " ) = " << bin(z) << '\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
参阅
(C++20) |
寻找不小于给定值的最小的二的整数次幂 (函数模板) |
(C++20) |
计算逐位右旋转的结果 (函数模板) |
(C++20) |
寻找表示给定值所需的最小位数 (函数模板) |
(C++20) |
检查一个数是否为 2 的整数次幂 (函数模板) |