本文共 637 字,大约阅读时间需要 2 分钟。
1.从最高位开始依次输出:把1左移31位,就是最高比特位,再&1,进行判断0或1;循环直到最低位。
#include#include int showDataBits(int x){ int i = 31; for (i = 31; i>=0; i--) { if (x&(1<
结果是:
2.通过异或^求出两个数中的不同数,然后计数有多少位不同。输入例子: 1999 2299 。输出结果为:7.
int main(){ int a = 1999; int b = 2299; int count = 0; int num= a^b;//相异为1,相同为0。求出ab中不同位。 while( num) { count++; num = num&(num - 1);//统计1的位数。 } printf("%d\n", count); system("pause"); return 0;}
通过函数实现:
#include#include int countBit(int i){ int n = 0; while (i){ i = i&(i - 1); n++; } return n;}int main(){ int n=countBit(1999 ^ 2299); printf("%d", n); system("pause"); return 0;}