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

35,036

Solution 1

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.

Solution 2

sorry - not enough reputation to comment but found previous answer is not fully correct. Actually, the nice light way to code it should be :

void p(byte X) { if (X < 10) {Serial.print("0");} ...

giving the code:

void p(byte X) {

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

   Serial.println(X, HEX);

}

And in the main code:

p(byte1);  // etc.

hope this helps

Solution 3

Use sprintf to print into a buffer (two chars per byte + null terminator):

byte byte1 = 0xA2;
byte byte2 = 0x05;
byte byte3 = 0x00;
char s[7];
sprintf(s, "%02x\n%02x\n%02x", byte1, byte2, byte3);
Serial.println(s);

Added new lines in between to get each on new line. About '%02x', the % means here comes formatting information, 0 means to pad with 0, 2 means pad input until 2 characters wide and x means give me this as hexadecimal.

For other formatting options see http://linux.die.net/man/3/sprintf

Solution 4

The lowest footprint in Memory, Code and runtime would be classic bit playing

byte b;
Serial.print(b>>4,  HEX);
Serial.print(b&0x0F,HEX);

Which is working fine on any 8bit type. For any other mask also the first line to

Serial.print((b>>4)&0x0F,  HEX);
Share:
35,036
Backo
Author by

Backo

Updated on November 24, 2020

Comments

  • Backo
    Backo over 3 years

    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?

  • Backo
    Backo over 10 years
    With the sprintf function (as @Retired Ninja said in a previous comment) it is more simple... why should I use your code?
  • JackCColeman
    JackCColeman over 10 years
    @Backo, load module size. That is, how much code does sprintf generate for your embedded system? If your sketch gets too large you will have to give-up some luxuries. But, for a small sketch whatever works is obviously acceptable.
  • Ross Rogers
    Ross Rogers over 8 years
    X < 10 ? 16 maybe, but not 10;
  • izak
    izak almost 8 years
    Agreed, just modify it to test for < 0x10 and you're done :-)