无符号与有符号数之间的强制转换

#include 

int main(){
	unsigned int a = 0xffffffff;
	int b = a;
	printf("%u %d %u %d\n",a,a,b,b);


	int a2 = -1;
	unsigned int b2 = a2;
	printf("%u %d %u %d\n",a2,a2,b2,b2);


	unsigned char a1 = 0xff;
	char b1 = a1;
	printf("%u %d %u %d\n",(int)a1,(int)a1,(int)b1,(int)b1);
	printf("%u %d %u %d\n",(unsigned int)a1,(unsigned int)a1,(unsigned int)b1,(unsigned int)b1);

	char a3 = -1;
	unsigned char b3 = a3;
	printf("%u %d %u %d\n",(int)a3,(int)a3,(int)b3,(int)b3);
	printf("%u %d %u %d\n",(unsigned int)a3,(unsigned int)a3,(unsigned int)b3,(unsigned int)b3);
	return 0;
}

运行结果为:

4294967295 -1 4294967295 -1
4294967295 -1 4294967295 -1
255 255 4294967295 -1
255 255 4294967295 -1
4294967295 -1 255 255
4294967295 -1 255 255
结论:

1、有符号数和无符号数之间的强制转换用一句话概括:直接copy!

2、unsigned char 无论是转int 还是unsigned int 高位直接补0

3、负数char 无论是转int 还是unsigned int 高位全补1

4、正数char 无论是转int 还是unsigned int 高位全补0

你可能感兴趣的:(无符号与有符号数之间的强制转换)