我试图在 C 中创建一个函数,您输入一个整数作为参数,该函数将使用 putchar()
输出其二进制值。因此,例如,在 32 位系统上,-1 作为参数将打印出字符“1”(或 int 49)三十二次(2 的补码)。
我的函数就是这样做的……但不知何故,应该打印出来的最后 4 个不是“1”(或 int 49)。但是,我得到了 int 17,然后是 int 1 三次。
代码如下:
int putbin(unsigned int b) {
int zero = 48;
int i = 0;
if (b == 0) {
putchar('0');
} else {
while (b != b % 2){
// putchar(b & 1 + 48);
printf("test %d:",i);
printf("%d ",b & 1 + zero);
printf("%d ",b);
printf("%d ",b & 1);
printf("%d ",zero);
newline();
b = b >> 1;
i++;
}
printf("last one ");
putchar(b + '0');
}
}
我根本不应该使用 printf()
,但为了关注变量,我暂时使用了它。
调用函数:
putbin(-1)
输出这个:
test 0:49 -1 1 48
test 1:49 2147483647 1 48
test 2:49 1073741823 1 48
test 3:49 536870911 1 48
test 4:49 268435455 1 48
test 5:49 134217727 1 48
test 6:49 67108863 1 48
test 7:49 33554431 1 48
test 8:49 16777215 1 48
test 9:49 8388607 1 48
test 10:49 4194303 1 48
test 11:49 2097151 1 48
test 12:49 1048575 1 48
test 13:49 524287 1 48
test 14:49 262143 1 48
test 15:49 131071 1 48
test 16:49 65535 1 48
test 17:49 32767 1 48
test 18:49 16383 1 48
test 19:49 8191 1 48
test 20:49 4095 1 48
test 21:49 2047 1 48
test 22:49 1023 1 48
test 23:49 511 1 48
test 24:49 255 1 48
test 25:49 127 1 48
test 26:49 63 1 48
test 27:17 31 1 48
test 28:1 15 1 48
test 29:1 7 1 48
test 30:1 3 1 48
last one 1
每次测试后的数值是我传递给函数 putchar()
的整数,以便打印出我的值。如您所见,一开始它正确输出了 49,即预期的“1”。然后不知何故变成了 17,然后是 1, 1, 1, 1。
之后的数值是 b
,这是我们想要打印 1 或 0 的整数值,每次迭代,我都右移它的所有位。
第三个数值是b & 1
。正如预期的那样,它输出 1。
第 4 个数值是变量 zero
,我定义为 int zero = 48
。我只是认为这可能是造成问题的原因。
我完全不明白为什么 1 + 48 (b & 1 + zero
) 会给我 17 而不是 49。
最佳答案
在 C 中,b & 1 + zero
等价于 b & (1 + zero)
因为 +
有更高的 precedence比&
。
您需要将 b & 1
括在括号中,以确保它在添加 zero
之前得到计算:
printf("%d ",(b & 1) + zero);
关于c - 不知何故,1 + 48 输出 17,然后是 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510989/