__builtin_popcount
是 GCC 和 Clang 编译器提供的一个 内置函数,用于计算一个整数的二进制表示中 1 的个数(即 population count)。它的作用是高效地统计一个整数的二进制形式中有多少个位是 1
。
函数原型:
int __builtin_popcount(unsigned int x);
- 参数:
x
是一个无符号整数(unsigned int
)。 - 返回值:返回
x
的二进制表示中1
的个数。
示例:
#include <iostream>
using namespace std;
int main() {
unsigned int x = 13; // 二进制表示为 1101
cout << __builtin_popcount(x) << endl; // 输出 3,因为 1101 中有 3 个 1
return 0;
}
为什么使用 __builtin_popcount
?
-
高效:
__builtin_popcount
是编译器内置函数,通常会被编译为一条 CPU 指令(如POPCNT
),因此速度非常快。- 如果手动实现统计
1
的个数,效率会低很多。
-
简洁:
- 使用
__builtin_popcount
可以让代码更简洁易读,避免手动实现复杂的位操作。
- 使用
手动实现 __builtin_popcount
:
如果不使用 __builtin_popcount
,我们可以手动实现一个函数来统计 1
的个数:
int popcount(unsigned int x) {
int count = 0;
while (x) {
count += x & 1; // 检查最低位是否为 1
x >>= 1; // 右移一位
}
return count;
}
- 这个函数通过循环和位操作统计
1
的个数。 - 但它的效率远低于
__builtin_popcount
,尤其是在需要频繁调用的场景中。
总结:
__builtin_popcount
是一个高效的函数,用于统计整数的二进制表示中1
的个数。- 如果使用的编译器不支持
__builtin_popcount
,可以手动实现,但效率会降低。