zl程序教程

您现在的位置是:首页 >  其它

当前栏目

char与unsigned char的区别

区别 char unsigned
2023-09-11 14:19:04 时间
1 #include <stdio.h>
2 int main()
3 {
4     unsigned char a = 128;
5     char b = a;
6     printf("a = %d , b = %d",a,b);
7     return 0; 
8 }

输出结果为 a = 128 , b = -128。

128的二进制表示为1000 0000

因为char是有符号类型,所以编译器把128,即1000 0000当成有符号数,即补码为1000 0000 (因为计算机中的有符号数都是用补码来表示的),其表示的十进制值为B2T = -2^8 = -128(此处参考csapp中第45面的公式2.3)。所以b = 128