std::popcount
来自 cppreference.cn
定义于头文件 <bit> |
||
template< class T > constexpr int popcount( T x ) noexcept; |
(C++20 起) | |
返回 x 值中 1 比特的数量。
此重载仅在 T
为无符号整型(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或扩展无符号整型)时参与重载决议。
目录 |
[编辑] 参数
x | - | 无符号整数类型的值 |
[编辑] 返回值
值 x 中 1 比特的数量。
[编辑] 注解
名称 popcount
是“population count”(总体计数)的缩写。
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_bitops |
201907L |
(C++20) | 位操作 |
[编辑] 示例
运行此代码
#include <bit> #include <bitset> #include <cstdint> #include <iostream> static_assert(std::popcount(0xFULL) == 4); int main() { for (const std::uint8_t x : {0, 0b00011101, 0b11111111}) std::cout << "popcount( " << std::bitset<8>(x) << " ) = " << std::popcount(x) << '\n'; }
输出
popcount( 00000000 ) = 0 popcount( 00011101 ) = 4 popcount( 11111111 ) = 8
[编辑] 参阅
(C++20) |
计算从最高有效位开始的连续 0 位的数量 (函数模板) |
(C++20) |
计算从最高有效位开始的连续 1 位的数量 (函数模板) |
(C++20) |
计算从最低有效位开始的连续 0 位的数量 (函数模板) |
(C++20) |
从最低有效位开始,计算连续的 1 位数 (函数模板) |
(C++20) |
检查一个数是否是 2 的整数次幂 (函数模板) |
返回被设置为 true 的位数 ( std::bitset<N> 的公共成员函数) | |
检查所有、任何或没有位被设置为 true ( std::bitset<N> 的公共成员函数) |