我知道有符号值的 2s 补码表示。但是二进制“10000000”如何变成十进制的 -128(使用 %d)。
对于 +64 二进制 rep = '01000000' 对于 -64 二进制 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;
}
输出:
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
*************************************
最佳答案
因为在您的编译器上,char
表示signed char
。
Char 只是一个很小的整数,通常在 0...255(对于 unsigned char
)或 -128...127(对于 signed char
) ).
将一个数转换为2补负数的方法是“反转位加1”
128 = “1000 0000”。反转位是“0111 1111”。添加 1 产量:“1000 0000”
关于c++ - 为什么,如果一个 char 被初始化为 1,然后左移 7 次并使用 %d 打印值,它会显示 -128 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3557720/