不知何故,1 + 48输出17,然后输出1

tru*_*ing 1 c

我正在尝试在C中创建一个函数,您输入一个整数作为参数,函数将使用putchar()其二进制值输出.因此,例如,在32位系统上,-1作为参数将打印出char"1"(或int 49)32次(2的补码).

我的功能就是这样......但不知何故,应该打印出来的最后4个不是"1"(或者是第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');
  }
}
Run Code Online (Sandbox Code Playgroud)

我根本不应该使用它printf(),但是为了密切注意我暂时使用它的变量.

调用函数:

putbin(-1)
Run Code Online (Sandbox Code Playgroud)

输出这个:

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
Run Code Online (Sandbox Code Playgroud)

每次测试后的数值是我传递给函数的整数putchar(),以便打印出我的.正如您所看到的,首先它正确地输出49或"1",如预期的那样.然后它以某种方式变为17然后1,1,1,1.

之后的数值是b,我们想要打印我们的1或0的整数值,每次迭代,我右移所有的位.

第三个数值是b & 1.正如预期的那样,它输出1.

第四个数值是zero我定义的变量int zero = 48.我只是觉得它可能是造成问题的人.

我很遗憾为什么1 + 48(b & 1 + zero)会给我17而不是49.

frs*_*slm 6

在C中,b & 1 + zero相当于b & (1 + zero)由于+具有更高的优先级&.

您需要b & 1在括号中括起来以确保在zero添加之前计算它:

printf("%d ",(b & 1) + zero);
Run Code Online (Sandbox Code Playgroud)