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

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

    Has this been found to be too slow?
    Small and crude, but it's all in the cache and CPU registers;

    void mybits(uint64_t x, unsigned char *idx)
    {
      unsigned char n = 0;
      do {
        if (x & 1) *(idx++) = n;
        n++;
      } while (x >>= 1);          // If x is signed this will never end
      *idx = (unsigned char) 255; // List Terminator
    }
    

    It's still 3 times faster to unroll the loop and produce an array of 64 true/false values (which isn't quite what's wanted)

    void mybits_3_2(uint64_t x, idx_type idx[])
    {
    #define SET(i) (idx[i] = (x & (1UL<

提交回复
热议问题