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).

Answer from Jonathan Leffler on Stack Overflow
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;
}
🌐
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.
Discussions

c - How to turn a hex string into an unsigned char array? - Stack Overflow
For example, I have a cstring "E8 ... to be converted into the equivalent unsigned char array {0xE8,0x48,0xD8,0xFF,0xFF,0x8B,0x0D}. What's an efficient way to do this? Thanks! EDIT: I can't use the std library... so consider this a C question. I'm sorry! ... This answers the original question, which asked for a C++ solution. You can use an istringstream with the hex manipulator: std::string hex_chars("E8 ... More on stackoverflow.com
🌐 stackoverflow.com
C - Convert Hex value to int and store in char array - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... int main(){ const char *hexstring = "f"; int number = (int)strtoul(hexstring, ... More on stackoverflow.com
🌐 stackoverflow.com
September 15, 2017
hash - Convert hex values to char array in C - Stack Overflow
I'm trying to implement a function which returns a string of hex values. I print the hex values out using this function: void print_hex(unsigned char *hash, const hashid type) { int i; fo... More on stackoverflow.com
🌐 stackoverflow.com
November 9, 2011
Hex value in string to char array/data array
Hello, I was unable to figure out how to transfer a hex value in string to char array. I have; String l = "731c8080"; // these value changes frequently in the loop String m = "58ed12a5" / /these value changes frequen… More on forum.arduino.cc
🌐 forum.arduino.cc
8
0
September 22, 2021
🌐
Stack Overflow
stackoverflow.com › questions › 26411447 › how-to-convert-hex-string-to-char-array-of-hex-in-c-c
How to convert hex string to char array of hex in C/C++ - Stack Overflow
October 16, 2014 - takes pointer to the input std::string hexString creates and returns unsigned char array as well as count of elements in the array.
🌐
YouTube
youtube.com › watch
How to Convert a Hex String to a Character Array in C+ + - YouTube
Learn how to effectively convert a hex string to a character array in C+ + using simple code examples and explanations.---This video is based on the quest...
Published: August 8, 2025
Views: 2
🌐
Oreate AI
oreateai.com › blog › converting-hexadecimal-strings-to-char-arrays-in-c › 066f5c97c8cb9b1c01109bddfc5c9639
Converting Hexadecimal Strings to Char Arrays in C - Oreate AI Blog
December 22, 2025 - We then loop through the string and use sscanf to convert every two characters into individual chars. Finally, we append a null character at the end of our array and print out the converted result. Now let's look at the second method involving bitwise operations. In this approach, we first convert each hexadecimal character into its corresponding four-bit binary value before casting it as a char variable.
🌐
GitHub
gist.github.com › xsleonard › 7341172
hex string to byte array, C · GitHub
int byteArrayToHexString(uint8_t *byte_array, int byte_array_len, char *hexstr, int hexstr_len) { int off = 0; int i; for (i = 0; i < byte_array_len; i ++) { off += snprintf(hexstr + off, hexstr_len - off, "x", byte_array[i]); } hexstr[off] = '\0'; return off; }
🌐
Agnostic Development
agnosticdev.com › blog-entry › c › testing-and-converting-hexadecimal-data-c
Testing and Converting Hexadecimal Data in C | Agnostic Development
November 24, 2017 - In researching the problem I found out that C has a very nice solution to this problem and that was to use sprintf to convert the buffer of hexadecimal data to a char array using the %x formatter tag to signify that we were in fact working with ...
Find elsewhere
Top answer
1 of 4
6
char * print_hex(const unsigned char *hash, const hashid type)
{
    const char lookupTable[]="0123456789abcdef";
    const size_t hashLength=mhash_get_block_size(type);
    size_t i;
    char * out=malloc(hashLength*2+1);
    if(out==NULL)
        return NULL;
    for (i = 0; i < hashLength; i++)
    {
        out[i*2]=lookupTable[hash[i]>>4];
        out[i*2+1]=lookupTable[hash[i]&0xf];
    }
    out[hashLength*2]=0;
    return out;
}

Obviously the caller is responsible for freeing the returned string.

Still, as @K-Ballo correctly said in his answer, you don't need to convert to string form two hashes to compare them, all you need in that case is just a memcmp.

int compare_hashes(const unsigned char * hash1, const hashid hash1type, const unsigned char * hash2, const hashid hash2type)
{
    if(hash1type!=hash2type)
        return 0;
    return memcmp(hash1, hash2, mhash_get_block_size(hash1type))==0;
}
2 of 4
4

How can I modify this function so that it returns a string?

You can print to a string variable using sprintf. I assume the hash size is fixed, so you know the size of your string would be number-of-chars-in-hash * 2 + 1. How to return that information is a typical problem in C, you can either return a malloced string that the user must then remember to free, or return a static string that will get replaced with the next call to the function (and makes the function non-reentrable). Personally I tend to avoid returning strings, instead having the function take a char* destination and a size.

(The goal being that I can compare the 2 values later)

Just compare the two hash variables in its raw form, you don't need strings for that.

🌐
Devcoons
devcoons.com › convert-a-char-array-of-hex-to-ascii-in-c
Convert a char array of HEX to ASCII in C – Devcoons
This function solves the case when we have a message which is represented as sequence of bytes in hex format in a string and we want to convert it back.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Hex value in string to char array/data array - Programming - Arduino Forum
September 22, 2021 - Hello, I was unable to figure out how to transfer a hex value in string to char array. I have; String l = "731c8080"; // these value changes frequently in the loop String m = "58ed12a5" / /these value changes frequently in the loop char buf[8]; Now I need like this: buf[0] = 0x73; // buf[ ] should be updated frequently based on the "l" and "m" values buf[1] = 0x1c; buf[2] = 0x80; buf[3] = 0x80; buf[4] = 0x58; buf[5] = 0xed; buf[6] = 0x12; buf[7] = 0xa5; Can i get some solution
🌐
Programming Idioms
programming-idioms.org › idiom › 176 › hex-string-to-byte-array › 3653 › c
Hex string to byte array, in C
const char* hexstring = "deadbeef"; size_t length = sizeof(hexstring); unsigned char bytearray[length / 2]; for (size_t i = 0, j = 0; i < (length / 2); i++, j += 2) bytearray[i] = (hexstring[j] % 32 + 9) % 25 * 16 + (hexstring[j+1] % 32 + 9) % 25; ... byte[] a = new byte[s.Length/2]; for (int i = 0, h = 0; h < s.Length; i++, h += 2) { a[i] = (byte) Int32.Parse(s.Substring(h, 2), System.Globalization.NumberStyles.HexNumber); } ... integer(kind=c_int8_t), dimension(:), allocatable :: a allocate (a(len(s)/2)) read(unit=s,fmt='(*(Z2))') a
🌐
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.
Top answer
1 of 16
83

As far as I know, there's no standard function to do so, but it's simple to achieve in the following manner:

#include <stdio.h>

int main(int argc, char **argv) {
    const char hexstring[] = "DEadbeef10203040b00b1e50", *pos = hexstring;
    unsigned char val[12];

     /* WARNING: no sanitization or error-checking whatsoever */
    for (size_t count = 0; count < sizeof val/sizeof *val; count++) {
        sscanf(pos, "%2hhx", &val[count]);
        pos += 2;
    }

    printf("0x");
    for(size_t count = 0; count < sizeof val/sizeof *val; count++)
        printf("%02x", val[count]);
    printf("\n");

    return 0;
}

Edit

As Al pointed out, in case of an odd number of hex digits in the string, you have to make sure you prefix it with a starting 0. For example, the string "f00f5" will be evaluated as {0xf0, 0x0f, 0x05} erroneously by the above example, instead of the proper {0x0f, 0x00, 0xf5}.

2 of 16
25

I found this question by Googling for the same thing. I don't like the idea of calling sscanf() or strtol() since it feels like overkill. I wrote a quick function which does not validate that the text is indeed the hexadecimal presentation of a byte stream, but will handle odd number of hex digits:

uint8_t tallymarker_hextobin(const char * str, uint8_t * bytes, size_t blen)
{
   uint8_t  pos;
   uint8_t  idx0;
   uint8_t  idx1;

   // mapping of ASCII characters to hex values
   const uint8_t hashmap[] =
   {
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //  !"#$%&'
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ()*+,-./
     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 01234567
     0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 89:;<=>?
     0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // @ABCDEFG
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // HIJKLMNO
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // PQRSTUVW
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // XYZ[\]^_
     0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // `abcdefg
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // hijklmno
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pqrstuvw
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // xyz{|}~.
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  // ........
   };

   bzero(bytes, blen);
   for (pos = 0; ((pos < (blen*2)) && (pos < strlen(str))); pos += 2)
   {
      idx0 = (uint8_t)str[pos+0];
      idx1 = (uint8_t)str[pos+1];
      bytes[pos/2] = (uint8_t)(hashmap[idx0] << 4) | hashmap[idx1];
   };

   return(0);
}
🌐
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)
🌐
Lua Ternary
nachtimwald.com › posts › hex encode and decode in c
Hex Encode and Decode in C | John's Blog
September 24, 2017 - Going back to binary two hex characters will always convert back to one binary value. char *bin2hex(const unsigned char *bin, size_t len) { char *out; size_t i; if (bin == NULL || len == 0) return NULL; out = malloc(len*2+1); for (i=0; i<len; i++) { out[i*2] = "0123456789ABCDEF"[bin[i] >> 4]; out[i*2+1] = "0123456789ABCDEF"[bin[i] & 0x0F]; } out[len*2] = '\0'; return out; } “0..F” is a const string here and we can index this as an array because it is an array.