STC printf打印 char問題


打印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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM