两个的都是用了移位操作符 为什么结果不一样 难道a在&的时候没有变成2进制计算???
两个的都是用了移位操作符 为什么结果不一样 难道a在&的时候没有变成2进制计算???
第一各图是对的。第二各图里,你把if (a & (1 << i) == 1) 改为if (a & (1 << i) ) 就对了。因为每次移位后1 << i不是1,而是2的i次方。
下面代码演示给你看计算过程:
#include <stdio.h>
int main()
{
int count =0;
int a = 13;
for (int i = 0; i < 32; ++i)
{
printf("i=%d, 1 << i = %d, a & (1 << i) = %d\n", i, 1 << i, a & (1 << i));
if (a & (1 << i) == 1)
++count;
}
printf("%d\n", count);
return 0;
}
//Output
i=0, 1 << i = 1, a & (1 << i) = 1
i=1, 1 << i = 2, a & (1 << i) = 0
i=2, 1 << i = 4, a & (1 << i) = 4
i=3, 1 << i = 8, a & (1 << i) = 8
i=4, 1 << i = 16, a & (1 << i) = 0
i=5, 1 << i = 32, a & (1 << i) = 0
i=6, 1 << i = 64, a & (1 << i) = 0
i=7, 1 << i = 128, a & (1 << i) = 0
i=8, 1 << i = 256, a & (1 << i) = 0
i=9, 1 << i = 512, a & (1 << i) = 0
i=10, 1 << i = 1024, a & (1 << i) = 0
i=11, 1 << i = 2048, a & (1 << i) = 0
i=12, 1 << i = 4096, a & (1 << i) = 0
i=13, 1 << i = 8192, a & (1 << i) = 0
i=14, 1 << i = 16384, a & (1 << i) = 0
i=15, 1 << i = 32768, a & (1 << i) = 0
i=16, 1 << i = 65536, a & (1 << i) = 0
i=17, 1 << i = 131072, a & (1 << i) = 0
i=18, 1 << i = 262144, a & (1 << i) = 0
i=19, 1 << i = 524288, a & (1 << i) = 0
i=20, 1 << i = 1048576, a & (1 << i) = 0
i=21, 1 << i = 2097152, a & (1 << i) = 0
i=22, 1 << i = 4194304, a & (1 << i) = 0
i=23, 1 << i = 8388608, a & (1 << i) = 0
i=24, 1 << i = 16777216, a & (1 << i) = 0
i=25, 1 << i = 33554432, a & (1 << i) = 0
i=26, 1 << i = 67108864, a & (1 << i) = 0
i=27, 1 << i = 134217728, a & (1 << i) = 0
i=28, 1 << i = 268435456, a & (1 << i) = 0
i=29, 1 << i = 536870912, a & (1 << i) = 0
i=30, 1 << i = 1073741824, a & (1 << i) = 0
i=31, 1 << i = -2147483648, a & (1 << i) = 0
3