测试环境:Win10 Professional , CodeBlocks 13.12
#includeint main(){ char ch1 = 0x01; char ch2 = 0x80; printf("ch1 = %x , size = %d\n",ch1, sizeof(ch1)); printf("ch2 = %x , size = %d\n",ch2, sizeof(ch2)); return 0;}//output:// ch1 = 1 , size = 1// ch2 = ffffff80 , size = 1
问题分析:
ch1 = 0 000 0001ch2 = 1 000 0000
由于ch1 , ch2 是char , 根据系统的不同,char 的类型可能不同,我的环境默认的char 是 signed char (即有符号数),所以第一位是符号位,而在调用 printf("%x",ch)时,会进行位扩展,由原有的 8位 -> 32位,在进行位扩展时,有符号数的符号位左移,无符号数则直接填充0,所以会出现下面的结果:
ch1 = 0000....0000 0 000 0001 = 0x00000001 = 0x1ch2 = 1111....1111 1 000 0000 = 0xffffff80 = 0xffffff80
而如果采用下面的写法:
#includeint main(){ unsigned char ch1 = 0x01; //无符号数 unsigned char ch2 = 0x80; printf("ch1 = %x , size = %d\n",ch1, sizeof(ch1)); printf("ch2 = %x , size = %d\n",ch2, sizeof(ch2)); return 0;}//output:// ch1 = 1 , size = 1// ch2 = 80 , size = 1
根据前面讲解:
ch1 = 0000....0000 0000 0001 = 0x1ch2 = 0000....0000 1000 0000 = 0x80