Find nth SET bit in an int

后端 未结 11 969
栀梦
栀梦 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:36

    Nowadays this is very easy with PDEP from the BMI2 instruction set. Here is a 64-bit version with some examples:

    #include 
    #include 
    #include 
    
    inline uint64_t nthset(uint64_t x, unsigned n) {
        return _pdep_u64(1ULL << n, x);
    }
    
    int main() {
        assert(nthset(0b0000'1101'1000'0100'1100'1000'1010'0000, 0) ==
                      0b0000'0000'0000'0000'0000'0000'0010'0000);
        assert(nthset(0b0000'1101'1000'0100'1100'1000'1010'0000, 1) ==
                      0b0000'0000'0000'0000'0000'0000'1000'0000);
        assert(nthset(0b0000'1101'1000'0100'1100'1000'1010'0000, 3) ==
                      0b0000'0000'0000'0000'0100'0000'0000'0000);
        assert(nthset(0b0000'1101'1000'0100'1100'1000'1010'0000, 9) ==
                      0b0000'1000'0000'0000'0000'0000'0000'0000);
        assert(nthset(0b0000'1101'1000'0100'1100'1000'1010'0000, 10) ==
                      0b0000'0000'0000'0000'0000'0000'0000'0000);
    }
    

提交回复
热议问题