Finding trailing 0s in a binary number

前端 未结 7 854
渐次进展
渐次进展 2021-01-06 00:32

How to find number of trailing 0s in a binary number?Based on K&R bitcount example of finding 1s in a binary number i modified it a bit to find the trailing 0s.

7条回答
  •  北海茫月
    2021-01-06 01:30

    Another approach (I'm surprised it's not mentioned here) would be to build a table of 256 integers, where each element in the array is the lowest 1 bit for that index. Then, for each byte in the integer, you look up in the table.

    Something like this (I haven't taken any time to tweak this, this is just to roughly illustrate the idea):

    int bitcount(unsigned x)
    {
       static const unsigned char table[256] = { /* TODO: populate with constants */ };
    
       for (int i=0; i>= 8)
       {
          unsigned char r = table[x & 0xff];
    
          if (r)
             return r + i*8;    // Found a 1...
       }
    
       // All zeroes...
       return sizeof(x)*8;
    }
    

    The idea with some of the table-driven approaches to a problem like this is that if statements cost you something in terms of branch prediction, so you should aim to reduce them. It also reduces the number of bit shifts. Your approach does an if statement and a shift per bit, and this one does one per byte. (Hopefully the optimizer can unroll the for loop, and not issue a compare/jump for that.) Some of the other answers have even fewer if statements than this, but a table approach is simple and easy to understand. Of course you should be guided by actual measurements to see if any of this matters.

提交回复
热议问题