Finding trailing 0s in a binary number

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

    Here's a way to compute the count in parallel for better efficiency:

    unsigned int v;      // 32-bit word input to count zero bits on right
    unsigned int c = 32; // c will be the number of zero bits on the right
    v &= -signed(v);
    if (v) c--;
    if (v & 0x0000FFFF) c -= 16;
    if (v & 0x00FF00FF) c -= 8;
    if (v & 0x0F0F0F0F) c -= 4;
    if (v & 0x33333333) c -= 2;
    if (v & 0x55555555) c -= 1;
    

提交回复
热议问题