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

后端 未结 2 1280
离开以前
离开以前 2021-01-21 03:00

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

2条回答
  •  长发绾君心
    2021-01-21 03:43

    2 points to keep in mind when using __builtin_ffs:

    1. in order to get the next bit, you need to clear the recently found bit
    2. if you are planning to use the result, for bit shifting or table indexing, you would most likely need to decrease it by one.
    while (m) {
        // Get the rightmost bit location. 
    
        int BitOffset = __builtin_ffs(m);
    
        // Clear the bit before the next iteration. 
        // Used in the loop condition.
    
        m = (m >> BitOffset) << BitOffset;
    
        // Do your stuff .....
    }
    

提交回复
热议问题