为什么,如果将char初始化为1然后左移7次并使用%d打印的值,它是否显示-128?

abh*_*ity 0 c c++

我知道签名值的2s补码表示.但二进制'10000000'如何成为-128十进制(使用%d).

for +64 binary rep ='01000000'for -64 binary rep ='11000000',这是'01000000'的2的补码

有人可以解释一下吗?

程序:

int main()
{
   char ch = 1;
   int count = 0;
   while(count != 8)
   {
     printf("Before shift val of ch = %d,count=%d\n",ch,count);
     ch = ch << 1;     

     printf("After  shift val of ch = %d,count=%d\n",ch,count);
     //printBinPattern(ch);  
     printf("*************************************\n");
     count++;
   }
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Before shift val of ch = 1, count=0
After  shift val of ch = 2, count=0
*************************************
...
... /* Output not shown */
Before shift val of ch = 32, count=5
After  shift val of ch = 64, count=5
*************************************
Before shift val of ch = 64, count=6
After  shift val of ch = -128, count=6
*************************************
Before shift val of **ch = -128**, count=7
After  shift val of ch = 0, count=7
*************************************
Before shift val of ch = 0, count=8
After  shift val of ch = 0, count=8
*************************************
Run Code Online (Sandbox Code Playgroud)

Jam*_*ran 14

因为在你的编译器上,char意味着signed char.

Char只是一个很小的整数,通常在0 ... 255(for unsigned char)或-128 ... 127(for signed char)的范围内.

将数字转换为2补码负数的方法是"反转位并加1"

128 ="1000 0000".反转位是"0111 1111".加1收益率:"1000 0000"

  • `signed char`的一般范围是[-128,**127**].'最小'范围是[-127,127]. (2认同)

fre*_*low 13

我知道签名值的2s补码表示.

好吧,显然你不是.1后跟所有0始终是最小的负数.