Find nth SET bit in an int

后端 未结 11 984
栀梦
栀梦 2020-12-14 18:14

Instead of just the lowest set bit, I want to find the position of the nth lowest set bit. (I\'m NOT talking about value on the nt

11条回答
  •  隐瞒了意图╮
    2020-12-14 18:40

    Building on the answer given by Jukka Suomela, which uses a machine-specific instruction that may not necessarily be available, it is also possible to write a function that does exactly the same thing as _pdep_u64 without any machine dependencies. It must loop over the set bits in one of the arguments, but can still be described as a constexpr function for C++11.

    constexpr inline uint64_t deposit_bits(uint64_t x, uint64_t mask, uint64_t b, uint64_t res) {
        return mask != 0 ? deposit_bits(x, mask & (mask - 1), b << 1, ((x & b) ? (res | (mask & (-mask))) : res)) : res;
    }
    
    constexpr inline uint64_t nthset(uint64_t x, unsigned n)  {
        return deposit_bits(1ULL << n, x, 1, 0);
    }
    

提交回复
热议问题