c++ - 位没有被重置?

标签 c++ bit-manipulation bit

我正在使用位向前扫描来检测 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);
    //          ^^^
}

关于c++ - 位没有被重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793091/

相关文章:

c++ - 远程过程调用 - 客户提供的服务

c++ - 使用两个字符串流但没有得到相同的结果

algorithm - 证明 XOR 不适用于查找丢失的数字(面试问题)?

c - 按位和求值

sql-server - SQL更改表中的列从位到整数

c++ - 输出速度

c++ - 代码在 Linux 上运行良好,但在 Windows 操作系统上提供不同的输出

c - 操作字符变量的位

javascript - 如何在 JavaScript 中创建图像的文本二进制表示?

C unsigned int 数组和位移