How to pad an ascii number with leading zeros? I need to include a 3 digit ascii representation of message length number in the message header, but I am having difficulty trying to pad the number with leading '0' zeros in order to keep the number of 'length' digits needing to be appended always 3 even when the message length is only one or two digits long.

Addendum:
The problem, more specifically, is how to left-pad a char array containing the number representation. 
I got as far as defining what and where, but I couldn't figure out how to shift the char[] contents right in order to insert the "0" at msglength[0].  (I tried using strcat, but that didn't work).

char msglength[4]          //(3 digits + nul)
for (int pad=1; pad&lt;=3-strlen(msglength); pad++)
{
    // add a leading zero char to msglength, but that involves
    // somehow shifting all its contents to the right
}
This is the kind of situation where printf() comes handy:



printf("%03d", number);


prints the number in the format you described. Alas, printf() is not
part of the standard Arduino API. But you can have it, nonetheless, at
least on AVR-based Arduinos, as it is provided by the avr-libc, which is
always linked with all Arduino programs. Some setup is needed to tell
avr-libc about where is its “standard output”. We can use the macro
fdev_setup_stream() to tell it to just push the bytes through
Serial.write():

static int Serial_write(char c, FILE *) {
    if (c == '\n') Serial.write('\r');  // convert LF -&gt; CRLF
    return Serial.write(c);
}

static FILE mystdout;

void setup() {
    Serial.begin(9600);
    stdout = &amp;mystdout;
    fdev_setup_stream(stdout, Serial_write, NULL, _FDEV_SETUP_WRITE);
}

void loop() {
    static int count;
    printf("%03d and counting...\n", count++);
    delay(500);
}


C.f. the manual of avr-libc's
stdio.h
for details.

Pros of this method:


printf() has plenty of options to control the formatting of your
messages.
It's very standard C, understood by anyone having programmed in that
language.


Cons:


This can make your compiled program bigger than it would be if
sticking with the Arduino API.
It's not the “Arduino way”.