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即可。