How to `Serial.print()` "full" hexadecimal bytes?

Backo picture Backo · Oct 2, 2013 · Viewed 31.7k times · Source

I am programming Arduino and I am trying to Serial.print() bytes in hexadecimal format "the my way" (keep reading for more information).

That is, by using the following code

byte byte1 = 0xA2;
byte byte2 = 0x05;
byte byte3 = 0x00;

Serial.println(byte1, HEX);
Serial.println(byte2, HEX);
Serial.println(byte3, HEX);

I get the following output in the Serial Monitor:

A2
5
0

However I would like to output the following:

A2
05
00

In words, I would like to print the "full" hexadecimal value including 0s (05 instead of 0 and 00 instead of 0).

How can I make that?

Answer

JackCColeman picture JackCColeman · Oct 2, 2013

Simple brute force method, is to write a routine as:

void p(char X) {

   if (X < 16) {Serial.print("0");}

   Serial.println(X, HEX);

}

And in the main code:

p(byte1);  // etc.