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

后端 未结 10 1917
北荒
北荒 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:25

    Assuming sparsity in number of set bits,

    int count = 0;
    unsigned int tmp_bitmap = x;        
    while (tmp_bitmap > 0) {
        int next_psn = __builtin_ffs(tmp_bitmap) - 1;
        tmp_bitmap &= (tmp_bitmap-1);
        id[count++] = next_psn;
    }
    

提交回复
热议问题