std::bit_floor
来自cppreference.com
在标头 <bit> 定义 | ||
template<class T > constexpr T bit_floor( T x )noexcept; | (C++20 起) | |
若 x 非零,则计算不大于 x 的最大的二的整数次幂。若 x 为零,则返回零。
此重载只有在 T
为无符号整数类型(即 unsignedchar、unsignedshort、unsignedint、unsignedlong、unsignedlonglong 或扩展无符号整数类型)时才会参与重载决议。
目录 |
[编辑]参数
x | - | 无符号整数值 |
[编辑]返回值
若 x 为零则为零;否则为不大于 x 的最大的二的整数次幂。
[编辑]注解
P1956R1 以前,为这个函数模板提出的名字是 floor2
。
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_int_pow2 | 202002L | (C++20) | 2 的整数次幂运算 |
[编辑]可能的实现
template<typename T, typename ... U> concept neither =(!std::same_as<T, U>&& ...); template<std::unsigned_integral T> requires neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>constexpr T bit_floor(T x)noexcept{if(x !=0)return T{1}<<(std::bit_width(x)-1);return0;} |
[编辑]示例
运行此代码
#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
[编辑]参阅
(C++20) | 寻找不小于给定值的最小的 2 的整数次幂 (函数模板) |
(C++20) | 计算逐位右旋转的结果 (函数模板) |
(C++20) | 寻找表示给定值所需的最小位数 (函数模板) |
(C++20) | 检查一个数是否为 2 的整数次幂 (函数模板) |