打印char 和long都有问题
在51单片机的KEIL程序中,使用printf("Voltage0:%d\r\n",123);串口打印输出,发现数据异常。
输出31488
Keil C51中的printf()与标准的C库的printf()函数稍有不同,在相应的帮助文档中有如下描述:
The optional characters l or L may immediately precede the type character to respectively specify long types for d, i, u, o, x, and X.
The optional characters b or B may immediately precede the type character to respectively specify char types for d, i, u, o, x, and X.
也就是说,使用C51的printf()函数打印%d/i/u/o/x/X格式时,你必须要指定该变量的存储格式l/L/b/B。
由于你的变量c为char类型,因此可将相应的代码改为如下:
printf("%bd\n",c);
printf("%bu\n",c);
printf("%bx\n",c);
即可得到正确的结果。
另:
若变量c为uint16时,则需将%bd等改为%hd;(这个是C51帮助文档里面没有的,后来自己总结出来的)
若变量c为uint32时,则需将%bd等改为%ld;
复杂方法:用sprintf先格式化字符串打出来。
简单方法:
关于占位符 8位 用bd/bu 16位用hd/hu 32用ld/lu/lx
其中51单片机 所占字节数short=int=2个字节
8位:%bd %bx
16位:%hd %hx
32位:%ld %lx
参考:
https://blog.csdn.net/qq_37333800/article/details/104794852
https://blog.csdn.net/pang9998/article/details/89405467?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control