How do you convert a byte array to a hexadecimal string in C?

Steve Walsh picture Steve Walsh · Jun 15, 2011 · Viewed 230.3k times · Source

I have:

uint8 buf[] = {0, 1, 10, 11};

I want to convert the byte array to a string such that I can print the string using printf:

printf("%s\n", str);

and get (the colons aren't necessary):

"00:01:0A:0B"

Any help would be greatly appreciated.

Answer

Mark Synowiec picture Mark Synowiec · Jun 15, 2011
printf("%02X:%02X:%02X:%02X", buf[0], buf[1], buf[2], buf[3]);

for a more generic way:

int i;
for (i = 0; i < x; i++)
{
    if (i > 0) printf(":");
    printf("%02X", buf[i]);
}
printf("\n");

to concatenate to a string, there are a few ways you can do this... i'd probably keep a pointer to the end of the string and use sprintf. you should also keep track of the size of the array to make sure it doesnt get larger than the space allocated:

int i;
char* buf2 = stringbuf;
char* endofbuf = stringbuf + sizeof(stringbuf);
for (i = 0; i < x; i++)
{
    /* i use 5 here since we are going to add at most 
       3 chars, need a space for the end '\n' and need
       a null terminator */
    if (buf2 + 5 < endofbuf)
    {
        if (i > 0)
        {
            buf2 += sprintf(buf2, ":");
        }
        buf2 += sprintf(buf2, "%02X", buf[i]);
    }
}
buf2 += sprintf(buf2, "\n");