给定一个 unsigned int,我必须执行以下操作:
- 计算设置为 1 的位数
- 找到最左边1位的索引
- 找到最右边1位的索引
(操作不应依赖于体系结构)。
我已经使用按位移位完成了此操作,但我必须迭代几乎所有位(es.32) 。
例如,计算 1:
unsigned int number= ...;
while(number != 0){
if ((number & 0x01) != 0)
++count;
number >>=1;
}
其他操作类似。
所以我的问题是:有没有更快的方法来做到这一点?
如果你想要fastest这样,您将需要使用非便携式方法。
Windows/MSVC:
- _BitScanForward() https://learn.microsoft.com/en-us/cpp/intrinsics/bitscanforward-bitscanforward64
- _BitScanReverse() https://learn.microsoft.com/en-us/cpp/intrinsics/bitscanreverse-bitscanreverse64
- __popcnt() https://learn.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64
GCC:
- __内置_ffs() http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
- __builtin_ctz() http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
- __builtin_clz() http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
- __builtin_popcount() http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
这些通常直接映射到本机硬件指令。所以它不会比这些快得多。
但由于它们没有 C/C++ 功能,因此只能通过编译器内部函数访问它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)