计数位或找到合适有效的位运算|最左边的人 [英] Efficient bitwise operations for counting bits or find the right|left most ones
问题描述
由于一个unsigned int,我必须执行以下操作:
Given an unsigned int, I have to implement the following operations :
- 计数设为1位的数量
- 找到的索引最左边的1位
- 找到的指数右击最1位
(操作不宜架构家属)。
(the operation should not be architecture dependents).
我做这个使用逐转变,但我有过几乎所有的位迭代(es.32)。
例如,数1的:
I've done this using bitwise shift, but I have to iterate through almost all the bits(es.32) . For example, counting 1's:
unsigned int number= ...;
while(number != 0){
if ((number & 0x01) != 0)
++count;
number >>=1;
}
其他人的操作都是类似的。
The others operation are similar.
所以我的问题是:有没有更快的方式做到这一点。
So my question is: is there any faster way to do that?
推荐答案
如果您想要的最快的话,你就需要使用不可移植的方法。
If you want the fastest way, you will need to use non-portable methods.
的Windows / MSVC:
- _BitScanForward()
- _BitScanReverse()
- __popcnt()
GCC:
- __builtin_ffs()
- __builtin_ctz()
- __builtin_clz()
- __builtin_popcount()
这些通常直接映射到本地硬件的说明。所以它不会比这快得多。
These typically map directly to native hardware instructions. So it doesn't get much faster than these.
但由于有对他们没有C / C ++的功能,他们只能通过编译器内在函数访问。
But since there's no C/C++ functionality for them, they're only accessible via compiler intrinsics.
这篇关于计数位或找到合适有效的位运算|最左边的人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!