Finding trailing 0s in a binary number

前端 未结 7 903
渐次进展
渐次进展 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:22

    Should be:

    int bitcount(unsigned char x)
    {
      int b;
      for(b=0; b<7; x>>=1)
      {
        if(x&1)
          break;
        else
          b++;
      }
      return b;
    }
    

    or even

    int bitcount(unsigned char x)
    {
      int b;
      for(b=0; b<7 && !(x&1); x>>=1) b++;
      return b;
    }
    

    or even (yay!)

    int bitcount(unsigned char x)
    {
      int b;
      for(b=0; b<7 && !(x&1); b++) x>>=1;
      return b;
    }
    

    or ...

    Ah, whatever, there are 100500 millions methods of doing this. Use whatever you need or like.

提交回复
热议问题