int main()
{
    char arr[4];
    arr[0] = 0x11;
    arr[1] = 0xc0;
    arr[2] = 0x0c;
    arr[3] = 0x00;

    size_t len = sizeof(arr) / sizeof(*arr);

    char* str = (char*)malloc(len * 2 + 1);
    for (size_t i = 0; i < len; i++)
    {
        const static char table[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c','d','e','f' };

        unsigned char c = (unsigned char)(arr[i]);
        unsigned int lowbyte = c & 0x0f;
        unsigned int highbyte = (c >> 4) & 0x0f;

        str[2 * i] = table[highbyte];
        str[2 * i + 1] = table[lowbyte];
    }

    str[2 * len] = '\0';

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

    return 0;
}
Answer from selbie on Stack Overflow
Discussions

javascript - Convert a Char Array to a String - Stack Overflow
How do you convert an array of characters to a string in JavaScript? var s = ['H', 'e', 'l', 'l', 'o']; // How to convert s to a string? More on stackoverflow.com
🌐 stackoverflow.com
Convert a HexaDecimal char array to a Char Array Or String in C - Post.Byes
Please help me in doing this Things ... 0d6963f7d28e17f 72 So it is skipping many characters in between... please help me converting this hexadecimal Char array in to a String... More on post.bytes.com
🌐 post.bytes.com
March 12, 2011
Char array to hex string C++ - Stack Overflow
I searched char* to hex string before but implementation I found adds some non-existent garbage at the end of hex string. I receive packets from socket, and I need to convert them to hex strings fo... More on stackoverflow.com
🌐 stackoverflow.com
Hex String to char* array C++ - Stack Overflow
I convert a char* into hex string with this code char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C','D','E','F' }; std::string hex_str; for (int i =... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 11
18

You can't fit 5 bytes worth of data into a 4 byte array; that leads to buffer overflows.

If you have the hex digits in a string, you can use sscanf() and a loop:

#include <stdio.h>
#include <ctype.h>

int main()
{
    const char *src = "0011223344";
    char buffer[5];
    char *dst = buffer;
    char *end = buffer + sizeof(buffer);
    unsigned int u;

    while (dst < end && sscanf(src, "%2x", &u) == 1)
    {
        *dst++ = u;
        src += 2;
    }

    for (dst = buffer; dst < end; dst++)
        printf("%d: %c (%d, 0x%02x)\n", dst - buffer,
               (isprint(*dst) ? *dst : '.'), *dst, *dst);

    return(0);
}

Note that printing the string starting with a zero-byte requires care; most operations terminate on the first null byte. Note that this code did not null-terminate the buffer; it is not clear whether null-termination is desirable, and there isn't enough space in the buffer I declared to add a terminal null (but that is readily fixed). There's a decent chance that if the code was packaged as a subroutine, it would need to return the length of the converted string (though you could also argue it is the length of the source string divided by two).

2 of 11
3

I would do something like this;

// Convert from ascii hex representation to binary
// Examples;
//   "00" -> 0
//   "2a" -> 42
//   "ff" -> 255
// Case insensitive, 2 characters of input required, no error checking
int hex2bin( const char *s )
{
    int ret=0;
    int i;
    for( i=0; i<2; i++ )
    {
        char c = *s++;
        int n=0;
        if( '0'<=c && c<='9' )
            n = c-'0';
        else if( 'a'<=c && c<='f' )
            n = 10 + c-'a';
        else if( 'A'<=c && c<='F' )
            n = 10 + c-'A';
        ret = n + ret*16;
    }
    return ret;
}

int main()
{
    const char *in = "0011223344";
    char out[5];
    int i;

    // Hex to binary conversion loop. For example;
    // If in="0011223344" set out[] to {0x00,0x11,0x22,0x33,0x44}
    for( i=0; i<5; i++ )
    {
        out[i] = hex2bin( in );
        in += 2;
    }
    return 0;
}
🌐
Post.Byes
post.bytes.com › home › forum › topic › convert a hexadecimal char array to a char array or string in c
Convert a HexaDecimal char array to a Char Array Or String in C - Post.Byes
March 12, 2011 - Please help me in doing this Things I tried Trial-1 unsigned char in[64]=0; int tempValue[64]; for (i = 0; i < 16; i++){ sprintf(&tempVa lue[i],"x", (unsigned char)mdContext->digest[i]); in[i]=(unsigned char)tempValue[i]; } printf("%s\n\n\ n",in); This prints 90593d4bd9372e7 7 But Original content is 900150983cd24fb 0d6963f7d28e17f 72 So it is skipping many characters in between... please help me converting this hexadecimal Char array in to a String
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 176665-convert-hex-byte-array-hex-char*.html
Convert hex byte array to hex char*
November 1, 2018 - Do you reeeeeeeeeeeeeeeeeeeally ... it in hex? Either way I would suggest using the %x specifier for printf in a loop (either printf to the screen or sprintf to make a string); if you're planning to make a string out of it, you will need more space allocated, because the byte aa and the string "aa" aren't compatible with each other. Yes ,I want to convert this byte array to char* that I can ...
Find elsewhere
🌐
GitHub
gist.github.com › xsleonard › 7341172
hex string to byte array, C · GitHub
char* barray2hexstr (const unsigned char* data, size_t datalen) { size_t final_len = datalen * 2; char* chrs = (unsigned char *) malloc((final_len + 1) * sizeof(*chrs)); unsigned int j = 0; for(j = 0; j<datalen; j++) { chrs[2*j] = (data[j]>>4)+48; chrs[2*j+1] = (data[j]&15)+48; if (chrs[2*j]>57) chrs[2*j]+=7; if (chrs[2*j+1]>57) chrs[2*j+1]+=7; } chrs[2*j]='\0'; return chrs; } ... It is very nice, but it does not check if the hex string is an actual hex string (for example "3FZP").
🌐
Teensy Forum
forum.pjrc.com › home › forums
Array of hex to char string
October 18, 2016 - Community of Electronics Enthusiasts Using Teensy
🌐
Stack Overflow
stackoverflow.com › questions › 28501325 › hex-string-to-char-array-c
Hex String to char* array C++ - Stack Overflow
how can i get a reverse conversion from hex string to original data? ... what is data? If you have a char* and you want to convert it to a string you can use the exisiting string constructor.
🌐
GitHub
gist.github.com › stigok › 1737e05ef2c02cb03e7e584a8145b77e
C program demonstrating byte array to hex string · GitHub
C program demonstrating byte array to hex string · Raw · hexstr.c · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Ondrovo
bits.ondrovo.com › hexc.html
Hex to C array - Ondrovo.com
Paste hex string. Characters outside 0-9a-fA-F and anything after | is discarded (hexdump). Hex digit count must be even.
Top answer
1 of 4
3

If all you need to do is print the values, then you do not need to do any conversion. Just use printf %.2xon the original array.

int main (void) {
    int i;
    unsigned char key[16] = "1234567812345678";
    for(i = 0; i < 16; i++)
        printf("%.2x", key[i]);
    return 0;
}

Even if you want to use the array in some other function, the actual bytes stored in key are the ascii characters, i.e. 0x31 0x32 etc. You can generally directly use the array key

Edit: To store the output in a character array, you can use the sprintf function.

char hex[33];
for(i = 0; i < 16; i++)
    sprintf(hex+2*i, "%.2x", key[i]);

Also note that the original array key should be 17 bytes to account for the \0 at the end.

2 of 4
1

Here is my take on it - the phex() function converts any data in memory into a newly allocated string containing the hex representation.

The main() function shows an example usage. The output is "31323334353637383930" for the example data.

#include <stdlib.h> /* malloc() */
#include <stdio.h>  /* sprintf() */
#include <string.h> /* strlen(), in the example main() */

/*
 * Return a hex string representing the data pointed to by `p`,
 * converting `n` bytes.
 *
 * The string should be deallocated using `free()` by the caller.
 */
char *phex(const void *p, size_t n)
{
    const unsigned char *cp = p;              /* Access as bytes. */
    char *s = malloc(2*n + 1);       /* 2*n hex digits, plus NUL. */
    size_t k;

    /*
     * Just in case - if allocation failed.
     */
    if (s == NULL)
        return s;

    for (k = 0; k < n; ++k) {
        /*
         * Convert one byte of data into two hex-digit characters.
         */
        sprintf(s + 2*k, "%02X", cp[k]);
    }

    /*
     * Terminate the string with a NUL character.
     */
    s[2*n] = '\0';

    return s;
}

/*
 * Sample use of `phex()`.
 */
int main(void)
{
    const char *data = "1234567890";               /* Sample data */
    char *h = phex(data, strlen(data));  /* Convert to hex string */

    if (h != NULL)
        puts(h);                                  /* Print result */

    free(h);                             /* Deallocate hex string */
    return 0;
}
Top answer
1 of 16
123
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 doesn't 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");
2 of 16
47

For completude, you can also easily do it without calling any heavy library function (no snprintf, no strcat, not even memcpy). It can be useful, say if you are programming some microcontroller or OS kernel where libc is not available.

Nothing really fancy you can find similar code around if you google for it. Really it's not much more complicated than calling snprintf and much faster.

#include <stdio.h>

int main(){
    unsigned char buf[] = {0, 1, 10, 11};
    /* target buffer should be large enough */
    char str[12];

    unsigned char * pin = buf;
    const char * hex = "0123456789ABCDEF";
    char * pout = str;
    int i = 0;
    for(; i < sizeof(buf)-1; ++i){
        *pout++ = hex[(*pin>>4)&0xF];
        *pout++ = hex[(*pin++)&0xF];
        *pout++ = ':';
    }
    *pout++ = hex[(*pin>>4)&0xF];
    *pout++ = hex[(*pin)&0xF];
    *pout = 0;

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

Here is another slightly shorter version. It merely avoid intermediate index variable i and duplicating laste case code (but the terminating character is written two times).

#include <stdio.h>
int main(){
    unsigned char buf[] = {0, 1, 10, 11};
    /* target buffer should be large enough */
    char str[12];

    unsigned char * pin = buf;
    const char * hex = "0123456789ABCDEF";
    char * pout = str;
    for(; pin < buf+sizeof(buf); pout+=3, pin++){
        pout[0] = hex[(*pin>>4) & 0xF];
        pout[1] = hex[ *pin     & 0xF];
        pout[2] = ':';
    }
    pout[-1] = 0;

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

Below is yet another version to answer to a comment saying I used a "trick" to know the size of the input buffer. Actually it's not a trick but a necessary input knowledge (you need to know the size of the data that you are converting). I made this clearer by extracting the conversion code to a separate function. I also added boundary check code for target buffer, which is not really necessary if we know what we are doing.

#include <stdio.h>

void tohex(unsigned char * in, size_t insz, char * out, size_t outsz)
{
    unsigned char * pin = in;
    const char * hex = "0123456789ABCDEF";
    char * pout = out;
    for(; pin < in+insz; pout +=3, pin++){
        pout[0] = hex[(*pin>>4) & 0xF];
        pout[1] = hex[ *pin     & 0xF];
        pout[2] = ':';
        if (pout + 3 - out > outsz){
            /* Better to truncate output string than overflow buffer */
            /* it would be still better to either return a status */
            /* or ensure the target buffer is large enough and it never happen */
            break;
        }
    }
    pout[-1] = 0;
}

int main(){
    enum {insz = 4, outsz = 3*insz};
    unsigned char buf[] = {0, 1, 10, 11};
    char str[outsz];
    tohex(buf, insz, str, outsz);
    printf("%s\n", str);
}
🌐
Arduino Forum
forum.arduino.cc › projects › programming
How to save HEX array to String? - Programming - Arduino Forum
October 10, 2021 - Hello everybody, I am receiving a HEX command from the UART, and debuging with softwareSerial and PC, the teraterm terminal output it looks like this: This is the piece of code that I am using to receive data and to …
🌐
Tomeko
tomeko.net › online_tools › ascii.php
ASCII to C-like array converter
0x and comma separator for output · See also: bin2hex.exe for Windows and bin2hex for Linux (source code)
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-string-exercise-27.php
JavaScript validation with regular expression: Convert ASCII to Hexadecimal format - w3resource
July 22, 2025 - Write a JavaScript function that maps each character’s char code to its hex value and concatenates the results. Write a JavaScript function that validates the input string before converting it to hexadecimal.