Leading zeros again

I found what is supposed to be a solution to printing leading zeros in this forum, but it doesn’t seem to work for me. It involves using sprintf to format the data in a buffer and then print the buffer.

I expect the code to produce

04 0A FA

but it is producing

4 A FA

it is using upper case for the output due to the ‘X’ in the format string, but it is not producing the leading zeros due to the ‘2’ in the format string.

Here is the code:

void setup() 
{
  Serial.begin(9600);
}

void loop() {
  u8 cmd[3];
  u8 cCount = 3;

  cmd[0] = 0x04;
  cmd[1] = 0x0a;
  cmd[2] = 0xfa;


  for (u8 i = 0; i < cCount; i++)
  {
    char buf[50];
    sprintf(buf, "%2X ", cmd[i]);
    Serial.print(buf);
    Serial.print(" ");
  }
  Serial.println();
}

If you want leading zeroes then you need to use "%02X"

marco_c:
If you want leading zeroes then you need to use "%02X"

Yes, that's all it needed.

Thank you for the help.