c++ 高效位运算函数 __builtin__
1. int __builtin_ffs (unsigned int x)
返回x的最后一位1的是从后向前第几位,lowbit操作(x &-x) (Find First Set)
int n = 1;//1
int m = 12;//1100
cout<<__builtin_ffs(n)<<endl;//输出1
cout<<__builtin_ffs(m)<<endl;//输出3
//对应三种不同的类型
int __builtin_ffs (unsigned int x)
Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.
int __builtin_ffsl (unsigned long)
Similar to __builtin_ffs, except the argument type is unsigned long.
int __builtin_ffsll (unsigned long long)
Similar to __builtin_ffs, except the argument type is unsigned long long.
2. int __builtin_clz (unsigned int x)
返回前导的0的个数。(Count Leading Zeros.)
int __builtin_clz (unsigned int x)
Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
int __builtin_clzl (unsigned long)
Similar to __builtin_clz, except the argument type is unsigned long.
int __builtin_clzll (unsigned long long)
Similar to __builtin_clz, except the argument type is unsigned long long.
3. int __builtin_ctz (unsigned int x)
返回拖尾0的个数(Count Leading Zeros.)
int __builtin_ctz (unsigned int x)
Returns the number of trailing 0-bits in x, starting at the least significant bit
position. If x is 0, the result is undefined.
int __builtin_ctzl (unsigned long)
Similar to __builtin_ctz, except the argument type is unsigned long.
int __builtin_ctzll (unsigned long long)
Similar to __builtin_ctz, except the argument type is unsigned long long.
4. int __builtin_popcount (unsigned int x)
返回二进制中1的个数(pop count)
int n = 24601; //二进制为110000000011001
cout<<__builtin_popcount(n)<<endl;//输出5
5.int __builtin_parity (unsigned int x)
返回x的奇偶校验位,1的个数为偶数为0,奇数为1