Keil C中如何直接打印char类型变量

Keil C开发中, 如果用%d去打印 char/unsigned char类型变量值, 会出现莫名奇妙的值。

当时在中文网上找了一通,竟然没有solution和合理解释!

 

由于项目比较急,所以只好用一个临时的办法, 即在char变量前加(int)强制类型转换。

后来我同事在keil官方网上找到了答案如下.

C51: PROBLEMS USING PRINTF
________________________________________
Information in this article applies to:
•	C51 All Versions
________________________________________
QUESTION
I can get the printf command to work with integers but not long integers or 8-bit integers. Why?
ANSWER
You must use the optional characters B or b and L or l immediately preceding the type character to respectively specify char or long versions of the integer types d, i ,u, o, x and X.
The following printf correctly prints 1, 2, and 3 as integers:
printf ("%d %d %d", (int) 1, (int) 2, (int) 3);
The following printf correctly prints 1, 2, and 3 as long integers:
printf ("%Ld %Ld %Ld", 1L, 2L, 3L);
The following printf correctly prints 1, 2, and 3 as chars:
printf ("%Bd %Bd %Bd", (char) 1, (char) 2, (char) 3);
The type casts on the numeric constants are important because they specify the number of bytes required for each numeric constant.

 

所以,在keil中,如打印8位长度的变量,直接用%bu或%Bu。

进一步总结下, printf函数实现中会根据%后面的字母做switch case处理。 有趣的是, 不同编译器的C lib实现printf的细节会有些差异。如gcc就不识别%b 或%B,打印char型变量直接用%d即可。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ltshan139

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值