char,unsigned char,unsigned short,有符号和无符号之间的转换

#include 
#include 
 
int main(void)
{
    char cA;
    unsigned char ucB;
    unsigned short usC;
 
    cA=128;
    ucB=128;
 
    usC=cA+ucB;
    printf("0X%x\n",usC);//1
 
    usC=cA+(short)ucB;
    printf("0X%x\n",usC);//2
 
    usC=(unsigned char)cA+ucB;
    printf("0X%x\n",usC);//3 
usC=cA+(char)ucB; 
printf("0X%x\n",usC);//4 
getchar(); 
return EXIT_SUCCESS;}

输出结果是 0x0 0x0 0x100 0xff00
Char 是-128~127,cA=128;   128=0x80;0x80看作有符号数其实就是-128,前3个就好理解了,第4个ucB=128=0x80,转成有符号的就是-128加上cA就是-256再转成us就是65536-256=65280.这里有一个是char转unsigned char 之中是不会丢失符号位的,符号位保留,当做一个位来看即可

你可能感兴趣的:(C/C++)