Finding trailing 0s in a binary number

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

    We can easily get it using bit operations, we don't need to go through all the bits. Pseudo code:

    int bitcount(unsigned x) {
        int xor = x ^ (x-1); // this will have (1 + #trailing 0s) trailing 1s
        return log(i & xor); // i & xor will have only one bit 1 and its log should give the exact number of zeroes
    }
    

提交回复
热议问题