位没有被重置?

Bits aren't being reset?

我正在使用位向前扫描来检测 unit64_t 中的设置位,使用我的程序中的每个设置位索引,清除设置位,然后继续查找下一个设置位。但是,当初始 uint64_t 值为:

0000000000001000000000000000000000000000000000000000000000000000

下面的代码没有重置第 52 位,因此它卡在了 while 循环中:

uint64_t bits64 = data;

//Detects index being 52
int32_t index = __builtin_ffsll(bits64);

while(0 != index){

    //My logic

    //Set bit isn't being cleared here
    clearNthBitOf64(bits64, index);

    //Still picks-up bit 52 as being set
    index = __builtin_ffsll(bits64);
}

void clearNthBitOf64(uint64_t& input, const uint32_t n) {
    input &= ~(1 << n);
}

来自the docs

— Built-in Function: int __builtin_ffs (int x)
Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.

你的clear函数差了一个,应该是:

clearNthBitOf64(bits64, index-1);

您的 clear 功能也溢出了。您需要确保您要移动的内容有足够的大小:

void clearNthBitOf64(uint64_t& input, const uint32_t n) {
    input &= ~(1ULL << n);
    //          ^^^
}

__builtin_ffsll "returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero." 需要将左移调整为~(1ULL << (n - 1))或将函数调用改为clearNthBitOf64(bits64, index - 1);