【c语言】有符号数据类型与无符号数据类型的计算

作者: CSDN博客  更新时间:2015-05-08 20:29:02  原文链接


// 有符号数据类型与无符号数据类型的计算

#include <stdio.h>

int main()
{
	char c;// -128~127
	unsigned char uc;//0~255
	unsigned short us;// 0~65535
	c = 128;
	uc = 128;
	// 字符型给短整型赋值有默认的类型提升,前边八位补其符号位
	us = c + uc;
	// us = -128 + 128 = 0即1111 1111 1000 0000 + 0000 0000 1000 0000 = 1 0000 0000 0000 0000即0x0
	printf("0x%x\n", us);
	us = (unsigned char)c + uc;//c:0~255
	// us = 128 + 128 = 256即0000 0000 1000 0000 + 0000 0000 1000 0000 = 0000 0001 0000 0000即0x100
	printf("0x%x\n", us);
	us = c + (char)uc;// uc:-128~127
	// us = -128 -128 = -256即1111 1111 1000 0000 + 1111 1111 1000 0000 = 1 1111 1111 0000 0000即0xff00
	printf("0x%x\n", us);
	return 0;
}

<img src="http://img.blog.csdn.net/20150508202923957?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhb3lhcWlhbjU1Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />