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.

Answer from Rishikesh Raje on Stack Overflow
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;
}
🌐
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.
🌐
Devcoons
devcoons.com › convert-a-char-array-of-hex-to-ascii-in-c
Convert a char array of HEX to ASCII in C – Devcoons
void hex_to_string(uint8_t* msg, size_t msg_sz, uint8_t* hex, size_t hex_sz) { memset(msg, '\0', msg_sz); if (hex_sz % 2 != 0 || hex_sz/2 >= msg_sz) return; for (int i = 0; i < hex_sz; i+=2) { uint8_t msb = (hex[i+0] <= '9' ? hex[i+0] - '0' : (hex[i+0] & 0x5F) - 'A' + 10); uint8_t lsb = (hex[i+1] ...
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;
}
Find elsewhere
🌐
Sling Academy
slingacademy.com › article › javascript-convert-string-to-hex-and-vice-versa
JavaScript: Convert String to Hex and Vice Versa - Sling Academy
June 17, 2023 - Iterate over each character in the string with a for loop. Use charCodeAt() to get the Unicode value of the character. Convert the Unicode value to hexadecimal using toString(16). Concatenate the hexadecimal values to form the hexadecimal string representation.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 176665-convert-hex-byte-array-hex-char*.html
Convert hex byte array to hex char*
November 1, 2018 - You can malloc exactly the right amount of space at the beginning, since you know you'll need 2n+1 bytes to store the string. [fn 1]If for some reason you're going to be doing this a zillion times and you don't want to call sprintf all that time, or you just think it would impress people, you can try to use a hash-table of characters and use the byte (or some bit-masked version of the byte) as an index to grab each character/pair of characters and copy them into your buffer.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 179960 › convert-char-to-hex
Convert char to hex | DaniWeb
March 5, 2009 - The example string looks like a DNS label encoding (3www6google3com0); if that is the intent, this single-digit approach is the correct, simple conversion. In essence your char array already has "hex" values in it, or decimal numbers or characters or however you wish to imagine them.
🌐
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.
🌐
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").
Top answer
1 of 3
2

Something very similar:

const char* string_to_hex(const char *str, char *hex, size_t maxlen)
{
    static const char* const lut = "0123456789ABCDEF";

    if (str == NULL) return NULL;
    if (hex == NULL) return NULL;
    if (maxlen == 0) return NULL;

    size_t len = strlen(str);

    char *p = hex;

    for (size_t i = 0; (i < len) && (i < (maxlen-1)); ++i)
    {
        const unsigned char c = str[i];
        *p++ = lut[c >> 4];
        *p++ = lut[c & 15];
    }

    *p++ = 0;

    return hex;
}

int main()
{
    char hex[20];
    const char *result = string_to_hex("0123", hex, sizeof(hex));
    return 0;
}
2 of 3
0

Just use the same function for std::string but with char *,

#include <iostream>                                                    
#include <cstdlib>                                                     
#include <cstring>                                                     
#include <string>                                                      

using namespace std;                                                   

char *string_to_hex(char *input) {                                     
    static const char *const lut = "0123456789ABCDEF";                 
    size_t len = strlen(input);                                        
    int k = 0;                                                         
    if (len & 1)                                                       
        return NULL;                                                   

    char *output = new char[(len / 2) + 1];                            

    for (size_t i = 0, j = 0; i < len; i++, j += 2) {                  
        const unsigned char c = input[i];                              
        output[j]     = lut[c >> 4];                                       
        output[j + 1] = lut[c & 15];                                   
    }                                                                  

    return output;                                                     
}                                                                      

std::string string_to_hex(const std::string &input) {                  
    static const char *const lut = "0123456789ABCDEF";                 
    size_t len = input.length();                                       

    std::string output;                                                
    output.reserve(2 * len);                                           
    for (size_t i = 0; i < len; ++i) {                                 
        const unsigned char c = input[i];                              
        output.push_back(lut[c >> 4]);                                 
        output.push_back(lut[c & 15]);                                 
    }                                                                  
    return output;                                                     
}                                                                      

int main() {                                                           
    string test = "Test";                                              
    std::string res(string_to_hex(test.c_str()));                      
    cout << res << endl;                                               
    res = string_to_hex(test);                                         
    cout << res << endl;                                               
}                                                                      
🌐
Stack Overflow
stackoverflow.com › questions › 38806958 › how-to-convert-char-array-to-hex-and-replace-it-in-with-substring-in-hex-array
c - How to convert char array to hex and replace it in with substring in hex array? - Stack Overflow
So that every time the only substring of the 'packet' array. ... Keep in mind that those are just numeric values. You may type them or view them as hex, but they are just numbers. – Retired Ninja Aug 6 '16 at 17:38 · What have you tried, and what was the result you got? There are lots of ways to do it. You might want to look up memmem() and memmove() or memcpy(), for example. Note that memmem() is neither standard C nor POSIX, but it is available on some non-Linux systems too (BSD, Mac OS X, AIX, …).
🌐
IncludeHelp
includehelp.com › c › convert-ascii-string-to-hexadecimal-string-in-c.aspx
Convert ASCII string (char[]) to hexadecimal string (char[]) in C
To convert an ASCII string to hex string, follow below-mentioned steps: Extract characters from the input string and convert the character in hexadecimal format using X format specifier, X gives 0 padded two bytes hexadecimal value of any value (like int, char).