std::bit_ceil
来自 cppreference.cn
定义于头文件 <bit> |
||
template< class T > constexpr T bit_ceil( T x ); |
(自 C++20 起) | |
计算不小于 x 的最小的 2 的整数次幂。
如果该值在 T
中不可表示,则行为未定义。仅当未发生未定义行为时,才允许在常量表达式中调用此函数。
此重载仅在 T
是无符号整数类型时参与重载解析(即,unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或扩展的无符号整数类型)。
内容 |
[编辑] 参数
x | - | 无符号整数类型的值 |
[编辑] 返回值
不小于 x 的最小的 2 的整数次幂。
[编辑] 异常
不抛出异常。
[编辑] 注解
在 P1956R1 之前,此函数模板的提议名称为 ceil2
。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_int_pow2 |
202002L |
(C++20) | 2 的整数次幂操作 |
[编辑] 可能的实现
请参见 libstdc++ (gcc) 和 libc++ (clang) 中的可能实现。
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_ceil(T x) noexcept { if (x <= 1u) return T(1); if constexpr (std::same_as<T, decltype(+x)>) return T(1) << std::bit_width(T(x - 1)); else { // for types subject to integral promotion constexpr int offset_for_ub = std::numeric_limits<unsigned>::digits - std::numeric_limits<T>::digits; return T(1u << (std::bit_width(T(x - 1)) + offset_for_ub) >> offset_for_ub); } } |
[编辑] 示例
运行此代码
#include <bit> #include <bitset> #include <iostream> int main() { using bin = std::bitset<8>; for (auto x{0U}; 0XA != x; ++x) std::cout << "bit_ceil( " << bin(x) << " ) = " << bin(std::bit_ceil(x)) << '\n'; }
输出
bit_ceil( 00000000 ) = 00000001 bit_ceil( 00000001 ) = 00000001 bit_ceil( 00000010 ) = 00000010 bit_ceil( 00000011 ) = 00000100 bit_ceil( 00000100 ) = 00000100 bit_ceil( 00000101 ) = 00001000 bit_ceil( 00000110 ) = 00001000 bit_ceil( 00000111 ) = 00001000 bit_ceil( 00001000 ) = 00001000 bit_ceil( 00001001 ) = 00010000
[编辑] 参见
(C++20) |
查找不大于给定值的最大的 2 的整数次幂 (函数模板) |