Find nth SET bit in an int

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

    Based on a method by Juha Järvi published in the famous Bit Twiddling Hacks, I tested this implementation where n and i are used as in the question:

        a = i - (i >> 1 & 0x55555555);
        b = (a & 0x33333333) + (a >> 2 & 0x33333333);
        c = b + (b >> 4) & 0x0f0f0f0f;
    
        r = n + 1;
        s = 0;
        t = c + (c >> 8) & 0xff;
    
        if (r > t) {
            s += 16;
            r -= t;
        }
    
        t = c >> s & 0xf;
    
        if (r > t) {
            s += 8;
            r -= t;
        }
    
        t = b >> s & 0x7;
    
        if (r > t) {
            s += 4;
            r -= t;
        }
    
        t = a >> s & 0x3;
    
        if (r > t) {
            s += 2;
            r -= t;
        }
    
        t = i >> s & 0x1;
    
        if (r > t)
            s++;
    
        return (s);
    

    Based on my own tests, this is about as fast as the loop on x86, whereas it is 20% faster on arm64 and probably a lot faster on arm due to the fast conditional instructions, but I can't test this right now.

提交回复
热议问题