The C Programming Language 练习题2-9

时间:2021-08-10 00:10:08

题目
在求对二的补码时,表达式x &= (x – 1)可以删除x中最右边值为1 的一个二进制位。请解释这样做的道理。用这一方法重写bitcount函数,以加快其执行速度。

题目分析
x &= (x-1)等效于 x = x & ( x - 1),x-1意味着最后一位必然会跟x相反,所以再与x相与最后一位肯定为0。
另外,根据2进制的特点,可以利用这一点来计算数中1的个数。

代码实现

#include <stdio.h>

int bitcountt(unsigned x);

int main()
{
    int i;

    i = 1767;
    printf("%d\n",bitcountt(i));

}

int bitcountt(unsigned x)
{
    int b;

    b = 0;
    while(x != 0)
        {
        b++;
        x &= (x-1);
        }
    return b;
}