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

前端 未结 8 1404
囚心锁ツ
囚心锁ツ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 07:04

    I actually think the fastest, simplest method is simply to loop around, but if we pass in a vector instead of later making a copy, it should be a little faster.

    void DQBitboard::bits(U64 bitboard, vector &res)
    {
        res.clear();   // Make sure vector is empty. Not necessary if caller does this!
        int bit = 0;
        while (bitboard)
        {
            if (bitboard & 1) 
                res.push_back(bit);
            bit++;
            bitboard >>= 1;
        }
    
        return res;
    }
    

    The multiply in the findfirst will cost a bit, so I doubt it's really worth it.

提交回复
热议问题