[英]Printing long value to hex with leading zeroes
I've been using this function to print int values with leading zeroes with 4 decimals, which has been working well.我一直在使用这个 function 打印带有前导零和 4 位小数的 int 值,效果很好。
Use Arduino IDE 1.8.12使用 Arduino IDE 1.8.12
void printHex(int num, int precision)
{
Serial.println(num);
char tmp[16];
char format[128];
sprintf(format, "%%.%dX", precision);
sprintf(tmp, format, num);
Serial.println(tmp);
}
Calling the function printHex(100,4)
prints out 0064
调用 function
printHex(100,4)
打印出0064
I now want to print long values with 5 decimals but its not as simple as I thought.我现在想打印 5 位小数的长值,但它不像我想象的那么简单。
Eg printHex(200000,5)
should print out 30D40
, and printHex(0,5)
should print 00000
例如
printHex(200000,5)
应该打印出30D40
,而printHex(0,5)
应该打印出00000
I tried changing int num to long num and its printing 5 digits, but the MSB is always 0我尝试将 int num 更改为 long num 并打印 5 位数字,但 MSB 始终为 0
Currently I'm getting 00D40
instead of 30D40
目前我得到的是
00D40
而不是30D40
Figured it out, had to use uint32_t and long in the sprintf想通了,不得不在 sprintf 中使用 uint32_t 和 long
void printHex(uint32_t num, int precision)
{
char tmp[16];
char format[128];
sprintf(format, "%%0%dlX", precision);
sprintf(tmp, format, num);
Serial.print(tmp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.