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