C语⾔printf(“%x,%d,%c“,)输出字符类型1.问题描述
printf("");函数打印 char 类型, 会出现打印错误,程序和结果如下:
#include <stdio.h>
int main()
{
char a, b,c,d;
a = 0x64;
b = 0x79;
c = 0x80;
d= 0xc8;
printf("%%x: a=%x; b=%x; c=%x; d=%x;\n", a, b, c,d);
a = 100;
b = 127;
c= 128;
d = 200;
printf("%%d: a=%d; b=%d; c=%d; d=%d;\n", a, b, c,d);
a = 100;
b = 127;
c = 128;
d = 200;
printf("%%u: a=%u; b=%u; c=%u; d=%u;\n", a, b, c,d);
return 0;
}
2.原因描述
%x, %d, %u  都是打印int 类型, 在本系统是32位,当char⼩于 128  及最⾼不为1  转换成32位int不会出错,
当char 类型 ⼤于128  最⾼为 1  转换的时候,把最⾼为当符号位处理,因此其他⾼3字节全为1。
3.解决办法
#include <stdio.h>
int main()
{
char a, b,c,d;
a = 0x64;
b = 0x79;
c = 0x80;
d= 0xc8;
printf("%%x: a=%hhx; b=%hhx; c=%hhx; d=%hhx;\n", a, b, c,d);
a = 100;
b = 127;
c= 128;
d = 200;
printf("%%d: a=%hhd; b=%hhd; c=%hhd; d=%hhd;\n", a, b, c,d);
a = 100;
b = 127;
c = 128;
d = 200;
printf("%%hhu: a=%hhu; b=%hhu; c=%hhu; d=%hhu;\n", a, b, c,d);
return 0;
}
注意:%hhx;只是将char 转换为32位后, 截取最低8位 然后按有符号数打印。
扩展:
类型转换会出现类似错误,程序结果如下图所⽰:
#include <stdio.h>
int main()
{
char a, b,c,d;
int i_a, i_b, i_c, i_d;
a = 0x64;
b = 0x79;
c = 0x80;
d= 0xc8;
i_a = a; i_b = b; i_c = c; i_d = d;
printf("%%x: a=%x; b=%x; c=%x; d=%x;\n", i_a, i_b, i_c,i_d);
a = 100;
b = 127;
c= 128;
d = 200;
i_a = a; i_b = b; i_c = c; i_d = d;
printf("%%d: a=%d; b=%d; c=%d; d=%d;\n", i_a, i_b, i_c, i_d);printf怎么输出字符
a = 100;
b = 127;
c = 128;
d = 200;
i_a = a; i_b = b; i_c = c; i_d = d;
printf("%%u: a=%u; b=%u; c=%u; d=%u;\n", i_a, i_b, i_c, i_d);
return 0;
}
解决:
#include <stdio.h>
int main()
{
char a, b,c,d;
int i_a, i_b, i_c, i_d;
a = 0x64;
b = 0x79;
c = 0x80;
d= 0xc8;
i_a = (unsigned char)a; i_b = (unsigned char)b; i_c = (unsigned char)c; i_d = (unsigned char)d; printf("%%x: a=%x; b=%x; c=%x; d=%x;\n", i_a, i_b, i_c,i_d);
a = 100;
b = 127;
c= 128;
d = 200;
i_a = (unsigned char)a; i_b = (unsigned char)b; i_c = (unsigned char)c; i_d = (unsigned char)d; printf("%%d: a=%d; b=%d; c=%d; d=%d;\n", i_a, i_b, i_c, i_d);
a = 100;
b = 127;
c = 128;
d = 200;
i_a = (unsigned char)a; i_b = (unsigned char)b; i_c = (unsigned char)c; i_d = (unsigned char)d; printf("%%u: a=%u; b=%u; c=%u; d=%u;\n", i_a, i_b, i_c, i_d);
return 0;
}
分析:类型转换,会将char转换为32位int 然后输出,会出现类似错误,
这⾥不能使⽤%hh 输出来解决,因为在转换已经转换错了,在截图打印也是错的,
这⾥只需要在转换时候,添加强制转换,标明转换类型就可以。
总结:
1.充分了解printf("%") 格式输出的含义和内部转换机制;
2.类型转换⼀定要添加强制类型转换;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。