我尝试确定最右边的第 n 个位集
if (value & (1 << 0)) { return 0; }
if (value & (1 << 1)) { return 1; }
if (value & (1 << 2)) { return 2; }
...
if (value & (1 << 63)) { return 63; }
如果需要比较64次。有没有更快的方法?
最佳答案
如果您使用的是 GCC,请使用 __builtin_ctz
或 __builtin_ffs
函数。 ( http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fffs-2894 )
如果您使用的是 MSVC,请使用 _BitScanForward
函数。参见 How to use MSVC intrinsics to get the equivalent of this GCC code? .
在 POSIX 中还有一个 ffs
函数。 ( http://linux.die.net/man/3/ffs )
关于c++ - 确定 64 位中最右边第 n 位集的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2377619/