1.代码示例
1.定义
std::popcount
定义于头文件 <bit>
template<class T>
constexpr int popcount(T x) noexcept;(C++20起加入)
返回值:返回1的位的个数.
2.g++ (C++20起引入) demo
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
for (const std::uint8_t i : { 0, 0b11111111, 0b00011101 }) {
std::cout << "popcount( " << std::bitset<8>(i) << " ) = "
<< std::popcount(i) << '\n';
}
}
3.GCC (__builtin_popcount)demo
#include <iostream>
using namespace std;
int dd;
int main(){
for(int i = 0 ;i < 100;i++){
dd = __builtin_popcount(i);
printf("i = %d, popcount = %d\n", i ,dd);
}
}