隐式转换:
- 窄类型自动转向宽类型 char ,short ,int ,long ,float,long long,double (同类型有符号比无符号窄,考点),窄类型转宽类型:补符号位,无符号数补0
- 整数默认为int,小数默认为double
- 所有运算int起
显示转换
- 强制类型转换
- 宽类型转窄类型:保留低数据
例题
- 宽类型转窄类型:保留低数据
int main()
{
int a = 1000;//0011 1110 1000
char b = a;//1110 1000->-0001 0111->-0001 1000->-24
printf("%d\n",b);//-24
return 0;
}
int main()
{
char a = -1;
char b = 255;//-1
unsigned char c = -1;//255
unsigned char d = 255;
int e = a;//-1
int f = b;//-1
int g = c;//255
int h = d;//255
printf("%d,%d,%d,%d\n",e,f,g,h);
return 0;
}
char:-128~127
unsigned char:0~255
- 窄类型变宽类型
int main()
{
char a = 10;//0000 1010 ->00000000 00000000 00000000 0000 1010
int b = a;
char c = -1;//1111 1111->11111111 11111111 11111111 11111111
int d = c;
unsigned char e = 200;//1100 1000->00000000 00000000 00000000 1100 1000
int f = e;
printf("%d,%d,%d\n",b,d,f);//10,-1,200
return 0;
}
- 考题
int main()
{
char a = 0x12; // 00000000 00000000 0001 0010 0001 0011
char b = 0x13;
printf("%d\n",a<<8|b);//19 注意<<优先级大于|
//18*256 + 19=
return 0;
}
- 窄类型自动转向宽类型,同类型有符号比无符号窄
int main()
{
unsigned short a = 10;
unsigned int b = 10;
if(a > -1)//-1默认为int,因此a也要转化成int(窄类型自动转向宽类型)
{//unsigned short , int -> int ,int -> 10>-1
printf("a>-1\n");
}
else
{
printf("a<-1\n");
}
if(b > -1)//unsigned int,int->unsigned int,unsigned int-> 10 > 2^32 -1
{//-1由int-> unsigned int
//-1二进制11111111 11111111 11111111 11111111
printf("b>-1\n");
}
else
{
printf("b<-1\n");//
}
return 0;
}
char y=128;
printf("%d,%u\n",x);//-128,4294967168
char:-128~127
char的8个比特位已经不够表示128,于是借一位即1 1000 0000->整型提升 1111 1111 1111 1111 1111 1111 1000 0000
int main()
{
unsigned int x=-1;
unsigned char y=-1;
unsigned short z=-1;
printf("%d,%u\n",x,x);//-1,4294967295
printf("%d,%u\n",y,y);//255,255
printf("%d,%u\n",z,z);//65535,65535
return 0;
}
char a=1,b='1';
printf("%c %c\n",a,b);// 输出ASCII为1的字符和字符'1'
注意
int==signed int,但是char不能简单以为是signed char
char相当于signed char或者unsigned char,取决于编译器不同,可以用下面的程序来验证
{
char c=0xff;
if(c==-1)
printf("signed");
else
printf("unsigned");
return 0;
}