int __builtin_ctz (unsignedint 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 (unsignedlong) Similar to __builtin_ctz, except the argument type is unsignedlong.
int __builtin_ctzll (unsignedlonglong) Similar to __builtin_ctz, except the argument type is unsignedlonglong.
这个函数作用是返回输入数二进制表示从最低位开始(右起)的连续的0的个数;如果传入0则行为未定义。三个函数分别用于unsigned int,unsigned long以及unsigned long long。
实现
int __builtin_ctzl(unsignedlong x) { for (int i = 0; i != 64; ++i) if (x >> i & 1) return i; return0; }
int __builtin_ctzl(unsignedlong x) { int r = 63; x &= ~x + 1; if (x & 0x00000000FFFFFFFF) r -= 32; if (x & 0x0000FFFF0000FFFF) r -= 16; if (x & 0x00FF00FF00FF00FF) r -= 8; if (x & 0x0F0F0F0F0F0F0F0F) r -= 4; if (x & 0x3333333333333333) r -= 2; if (x & 0x5555555555555555) r -= 1; return r; }
2、__builtin_clz
一共有三个函数,分别适用于不同的输入类型。
int __builtin_clz (unsignedint 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 (unsignedlong) Similar to __builtin_clz, except the argument type is unsignedlong.
int __builtin_clzll (unsignedlonglong) Similar to __builtin_clz, except the argument type is unsignedlonglong.
这个函数作用是返回输入数二进制表示从最高位开始(左起)的连续的0的个数;如果传入0则行为未定义。三个不同的函数分别用于unsigned int,unsigned long以及unsigned long long。
实现
int __builtin_clzl(unsignedlong x) { for (int i = 0; i != 64; ++i) if (x >> 63 - i & 1) return i; }
int __builtin_clzl(unsignedlong x) { int r = 0; if (!(x & 0xFFFFFFFF00000000)) r += 32, x <<= 32; if (!(x & 0xFFFF000000000000)) r += 16, x <<= 16; if (!(x & 0xFF00000000000000)) r += 8, x <<= 8; if (!(x & 0xF000000000000000)) r += 4, x <<= 4; if (!(x & 0xC000000000000000)) r += 2, x <<= 2; if (!(x & 0x8000000000000000)) r += 1, x <<= 1; return r; }
3、__builtin_ffs
一共有三个函数,分别适用于不同的输入类型。
int __builtin_ffs (unsignedint x) Returns one plus the index of the least significant 1-bit of x, orif x is zero, returns zero.
int __builtin_ffsl (unsignedlong) Similar to __builtin_ffs, except the argument type is unsignedlong.
int __builtin_ffsll (unsignedlonglong) Similar to __builtin_ffs, except the argument type is unsignedlonglong.
这个函数作用是返回输入数二进制表示的最低非0位的下标,下标从1开始计数;如果传入0则返回0。三个不同的函数分别用于unsigned int,unsigned long以及unsigned long long。