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

后端 未结 6 2113
星月不相逢
星月不相逢 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:28

    See here for the 32-bit version and other great bit-twiddling hacks.

    // this is like doing a sign-extension
    // if original value was   0x00.01yyy..y
    // then afterwards will be 0x00.01111111
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
    x |= (x >> 32);
    

    and after that you just need to return 64 - numOnes(x). A simple way to do that is numOnes32(x) + numOnes32(x >> 32) where numOnes32 is defined as:

    int numOnes32(unsigned int x) {
        x -= ((x >> 1) & 0x55555555);
        x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
        x = (((x >> 4) + x) & 0x0f0f0f0f);
        x += (x >> 8);
        x += (x >> 16);
        return(x & 0x0000003f);
    }
    

    I haven't tried out this code, but this should do numOnes64 directly (in less time):

    int numOnes64(unsigned long int x) {
         x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
         x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
         // collapse:
         unsigned int v = (unsigned int) ((x >>> 32) + x);
         v = ((v >> 4) + v) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
         v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
         return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
    }
    

提交回复
热议问题