内在地计算64位整数中的尾随零位? [英] Intrinsic to count trailing zero bits in 64-bit integers?

查看:83
本文介绍了内在地计算64位整数中的尾随零位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对先前有关位操作的一些问题的跟进.我修改了此网站中的代码,以枚举K个N位的字符串(x是当前int64_t,设置了K位,在此代码的末尾,它是字典上设置了K位的下一个整数):

this is sort of a follow up on some previous questions on bit manipulation. I modified the code from this site to enumerate strings with K of N bits set (x is the current int64_t with K bits set, and at the end of this code it is the lexicographically next integer with K bits set):

int64_t b, t, c, m, r,z;
b = x & -x;
t = x + b;
c = x^t;
// was m = (c >> 2)/b per link
z = __builtin_ctz(x);
m = c >> 2+z;
x = t|m;

只要的最低有效位在x的较低DWORD中,使用__builtin_ctz()进行的修改就可以正常工作,但是如果不是,则完全中断.可以通过以下代码看到这一点:

The modification using __builtin_ctz() works fine as long as the least significant one bit is in the lower DWORD of x, but if is not, it totally breaks. This can be seen with the following code:

for(int i=0; i<64; i++) printf("i=%i, ctz=%i\n", i, __builtin_ctz(1UL << i));

针对GCC版本4.4.7打印:

which prints for GCC version 4.4.7:

i=0, ctz=0
i=1, ctz=1
i=2, ctz=2

...

i=30, ctz=30
i=31, ctz=31
i=32, ctz=0

或对于icc版本14.0.0来说类似(除了i> 32会给出随机结果,而不是零).在这两种情况下,都可以使用除法而不是按2 + z进行平移,但是在我的Sandy Bridge Xeon上,它的速度要慢5倍.我应该为64位使用其他内部函数吗,还是必须做一些内联汇编程序?

or for icc version 14.0.0 something similar (except i>32 gives random results, not zero). Using division instead of shifting by 2+z works in both cases, but it's about 5x slower on my Sandy Bridge Xeon. Are there other intrinsics I should be using for 64-bit, or will I have to do some inline assembler?

谢谢!

推荐答案

__builtin_ctz接受类型为unsigned int的参数,该参数在大多数平台上为32位.

__builtin_ctz takes arguments of type unsigned int, which is 32-bits on most platforms.

如果long是64位,则可以使用__builtin_ctzl,它占用unsigned long.或者,您可以使用__builtin_ctzll加上unsigned long long-在这种情况下,您应该使用1ULL << i而不是1UL << i.

If long is 64 bits, you can use __builtin_ctzl which takes unsigned long. Or you can use __builtin_ctzll which takes unsigned long long - In this case you should use 1ULL << i instead of 1UL << i.

这篇关于内在地计算64位整数中的尾随零位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆