Get an array of the bit positions within a 64-bit integer

前端 未结 8 1368
囚心锁ツ
囚心锁ツ 2020-12-30 06:07

OK, it may sound a bit complicated, but this is what I\'m trying to do :

  • Take e.g. 10101010101
  • And return { 0, 2, 4, 6, 8, 10 }
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 06:48

    Here is another suggestion that can be profiled (can be combined with other suggestions for further optimization). Note, the loop here is O(number of set bits).

    vector bits_set (UINT64 data) 
    {
        UINT n;
        vector res;
        res.reserve(64);
        for (n = 0; data != 0; n++, data &= (data - 1))
        {
            res.push_back(log2(data & ~(data-1)));
        }
        return res;
    }
    

提交回复
热议问题