参考:http://gcc.gnu.org/onlinedocs/gcc-4.5.4/gcc/Other-Builtins.html

G++中有一些很实用的内置函数,在解决一些与位运算有关的问题时特别有用。
这些函数返回值均为int,函数名形如__built_xxx,参数均为无符号整形。

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.
返回右起第一个‘1’的位置,若x为0则返回0。(注意是位置,也就是说1<<(
_builtin_ffs(x)-1)==x&-x)

int __builtin_clz (unsigned int x) (即count left zero)
Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
返回左起第一个‘1’之前0的个数。(很有用,可以在时间内算出一个数化为二进制后的位数,但要注意这个只能处理正数)

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.
返回右起第一个‘1’之后的0的个数。

int __builtin_popcount (unsigned int x)
Returns the number of 1-bits in x.
返回‘1’的个数。(非常有用)

int __builtin_parity (unsigned int x)
Returns the parity of x, i.e. the number of 1-bits in x modulo 2.
返回‘1’的个数的奇偶性。

下面的函数与上面的类似,参数类型为unsigned long和unsigned long long

int _builtin_ffsl (unsigned long)
Similar to __builtin
ffs, except the argument type is unsigned long.

int _builtin_clzl (unsigned long)
Similar to __builtin
clz, except the argument type is unsigned long.

int _builtin_ctzl (unsigned long)
Similar to __builtin
ctz, except the argument type is unsigned long.

int _builtin_popcountl (unsigned long)
Similar to __builtin
popcount, except the argument type is unsigned long.

int _builtin_parityl (unsigned long)
Similar to __builtin
parity, 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.

int _builtin_clzll (unsigned long long)
Similar to __builtin
clz, except the argument type is unsigned long long.

int _builtin_ctzll (unsigned long long)
Similar to __builtin
ctz, except the argument type is unsigned long long.

int _builtin_popcountll (unsigned long long)
Similar to __builtin
popcount, except the argument type is unsigned long long.

int _builtin_parityll (unsigned long long)
Similar to __builtin
parity, except the argument type is unsigned long long.

Comments

comments powered by Disqus