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

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

    Here's something very simple which might be faster - no way to know without testing. Much will depend on the number of bits set vs. the number unset. You could unroll this to remove branching altogether but with today's processors I don't know if it would speed up at all.

    unsigned char idx[K+1]; // need one extra for overwrite protection
    unsigned char *dst=idx;
    for (unsigned char i = 0; i < 50; i++)
    {
        *dst = i;
        dst += x & 1;
        x >>= 1;
    }
    

    P.S. your sample output in the question is wrong, see http://ideone.com/2o032E

提交回复
热议问题