How to print 32-bit uint32_t as eight hex digits in Arduino
When using Arduino, you often want to print the hex value of a 32-bit value such as a uint32_t
, consisting of eight hex digits. For example, if you have uint32_t val = 9177025;
, you intend to print 008C07C1
.
In Arduino you can do that using Serial.printf()
with %08lx
as format specifier. Furthermore, you typically want to invert the byte order of the uint32_t
using __builtin_bswap32()
since it’s more inuitive to write the hex value MSB-first (big-endian) while most hardware platforms represent the uint32_t
as LSB-first (little-endian):
Serial.printf("val = %08lx\r\n", __builtin_bswap32(val));
When using printf, %x
means to format the value as hex whereas l
tells printf()
that the argument is a long
(32 bit) as opposed to an int
(16 bit). 08
means to pad the value with 0
s up to a length of 8
digits. If you would format 9177025
using just %x
, it would print 008C07C1
instead of 008C07C1
. This is why you need to use %08lx
instead.