参考:http://www.cnblogs.com/tgycoder/p/4218696.html
int main(void)
{
/* 一个字节 无符号范围为[0, 255],有符号范围为[ -128,0],[0,127] */
signed char b = -120;
signed short c = -60000;
unsigned char a;
unsigned short d;
a = (unsigned char)b;
d = (unsigned short)c;
printf("%d
", a); /* 136 = -120 + 256 */
printf("%d
", d); /* 5536 = - 60000 + 65536 */
return 0;
}
有符号数转换为无符号数时,负数转换为大的正数,相当于在原值上加上2的n次方,而正数保持不变
int main(void)
{
/* 两个字节 无符号范围为[0, 65535],有符号范围为[ -32768,0],[0,32767] */
signed char b = 0;
signed short c = 0;
unsigned char a = 128;
unsigned short d = 32768;
b = (signed char)a;
c = (unsigned short)d;
printf("%d
", b); /* -128 = 128 - 256*/
printf("%d
", c); /* -32768 = 32768 - 65536*/
return 0;
}
无符号数转换为有符号数时,对于小的数将保持原值,对于大的数将转换为负数,相当于原值减去2的n次方
当表达式中存在有符号数和无符号数类型时,所有的操作都自动转换为无符号类型。可见无符号数的运算优先级高于有符号数