GCC Bit-scan-forward to find next set bit?

笑着哭i 提交于 2019-12-24 05:47:15

问题


I have a uint64_t and I would like to find the index of the first set bit, reset it to zero and find the next set bit.

How do I know when to terminate? BSF on all zeros is undefined...

const uint64_t input = source;

if(0 != input){

    int32_t setIndex = GCC_BSF_INTRINSIC(input);

    while(setIndex != UNDEFINED???){

        //Do my logic

        //Reset
        input[setIndex] = 0;

        setIndex = BSF_Variant(input);
    }
}

Could somebody please help?


回答1:


The simplest would be to just check the input:

while (input) {
    int32_t index = __builtin_ffsll(input);
    // do stuff
}

More complicatedly, according to the docs 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.

Which lets you do:

for (int index  = __builtin_ffsll(input); 
     index; 
     index = __builtin_ffsll(input))
{
    // do stuff
}

Which accomplishes the same thing, you just have to repeat the __builtin_ffsll call, so it's more verbose and in my opinion doesn't contribute to clarity.



来源:https://stackoverflow.com/questions/32792365/gcc-bit-scan-forward-to-find-next-set-bit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!