How To Find The Leading Number Of Zero's In a Number using C

后端 未结 6 2117
星月不相逢
星月不相逢 2021-02-04 21:07

for example,if i have number 64,then its binary representation would be 0000 0000 0000 0000 0000 0000 0100 0000 so leading number of zero\'s is 25. remember i have to calculate

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-04 21:23

    I just found this problem at the top of the search results and this code:

    int pop(unsigned x) {
        unsigned n;
        n = (x >> 1) & 033333333333;
        x = x - n;
        n = (n >> 1) & 033333333333;
        x = x - n;
        x = (x + (x >> 3)) & 030707070707;
        return x % 63;
    }
    
    int nlz(unsigned x) {
        x = x | (x >> 1);
        x = x | (x >> 2);
        x = x | (x >> 4);
        x = x | (x >> 8);
        x = x | (x >>16);
        return pop(~x);
    }
    

    where pop counts 1 bits, is several times faster than the first (upvoted) answer.

    I didn't notice, question was about 64 bits numbers, so here:

    int nlz(unsigned long x) {
        unsigned long y;
        long n, c;
        n = 64;
        c = 32;
        do {
            y = x >> c;
            if (y != 0) {
                n = n - c;
                x = y;
            }
            c = c >> 1;
        } while (c != 0);
        return n - x;
    }
    

    is a 64 bits algorithm, again several times faster than the mentioned above.

提交回复
热议问题