如何在 Arduino 中将字节打印为两个十六进制数字
在嵌入式编程中,你经常想打印字节的十六进制值,由两个十六进制数字组成。例如,如果你有 uint8_t val = 14;,你打算打印 0x0E。
在 Arduino 中,你可以使用 Serial.printf() 以 %02x 作为格式说明符来实现:
print_byte_hex.ino
Serial.printf("val = %02x\r\n", val);使用 printf 时,%x 表示将值格式化为十六进制。02 表示用 0 填充值直到长度为 2 位数字。如果你只用 %x 格式化 14,它会打印 E 而不是 0E。这就是为什么你需要使用 %02x。
Check out similar posts by category:
Arduino, Electronics, Embedded, PlatformIO
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow