What is the fastest way to return the positions of all set bits in a 64-bit integer?

后端 未结 10 1899
北荒
北荒 2020-12-13 04:05

I need a fast way to get the position of all one bits in a 64-bit integer. For example, given x = 123703, I\'d like to fill an array idx[] = {0, 1, 2, 4,

10条回答
  •  伪装坚强ぢ
    2020-12-13 04:40

    Here's some tight code, written for 1-byte (8-bits), but it should easily, obviously expand to 64-bits.

    int main(void)
    {
        int x = 187;
    
        int ans[8] = {-1,-1,-1,-1,-1,-1,-1,-1};
        int idx = 0;
    
        while (x)
        {
            switch (x & ~(x-1))
            {
            case 0x01: ans[idx++] = 0; break;
            case 0x02: ans[idx++] = 1; break;
            case 0x04: ans[idx++] = 2; break;
            case 0x08: ans[idx++] = 3; break;
            case 0x10: ans[idx++] = 4; break;
            case 0x20: ans[idx++] = 5; break;
            case 0x40: ans[idx++] = 6; break;
            case 0x80: ans[idx++] = 7; break;
            }
    
            x &= x-1;
        }
    
       getchar();
       return 0;
    }
    

    Output array should be:

    ans = {0,1,3,4,5,7,-1,-1};
    

提交回复
热议问题