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
๐ŸŒ
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 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;
}
Discussions

Reading hex values from external file into an array
Each hexadecimal digit, called a nibble, is a value between 0 and 15, inclusive. You can multiply by 0x10 and add the digit, just like you did when you wrote a decimal integer decoder (I'm assuming you did this, because we all did this...) In this case, multiplying by 0x10 is the same as shifting up by 4 bits: x << 4. And adding the value can be done with a bitwise-or, since there is nothing in the low 4 bits to collide with: (x << 4) | nibble More on reddit.com
๐ŸŒ r/C_Programming
5
1
February 15, 2024
Storing Hex values in an int array C
Why would you ever need to do that? More on reddit.com
๐ŸŒ r/AskProgramming
9
3
March 23, 2018
Hexadecimal string to byte array in C - Stack Overflow
Sign up to request clarification or add additional context in comments. ... This is a good approach, but be aware that it will give an incorrect result if there is an odd number of digits in the hex string (the implicit zero will prefix the last digit, not the first, so "5ab5c" will be printed as 0x5ab50c rather than 0x05ab5c). 2010-08-05T07:02:58.773Z+00:00 ... @Geremia nope. Endianness only comes into play when you're reinterpreting byte arrays ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Convert array of numbers into single Hex value in c - Stack Overflow
using 'C' program I want to convert an array of numbers into a single Hex value and then into an array as mentioned below. input: `unsigned char no_a[12] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x0... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Instructables
instructables.com โ€บ design โ€บ software
HEX File to Array in C : 10 Steps - Instructables
June 13, 2022 - To load data from an Intel HEX format file I used several functions, open_file() to create a data stream, more commonly know as a file pointer, from the file I wanted to read. And hex_file_to_array(), to parse the hex file and extract the data.
๐ŸŒ
STMicroelectronics Community
community.st.com โ€บ t5 โ€บ stm32-mcus-products โ€บ hex-file-to-array-in-c-on-stm32f7 โ€บ td-p โ€บ 198533
Solved: HEX File to Array in C on STM32F7 - STMicroelectronics Community
July 22, 2021 - Typically you'd want to stage each line to a buffer, before checking the address and alignment, and you could eliminate 99.99% of hard faults. Check also the address you're writing at is blank. Hard Fault Handlers can return so one could do a try/catch type probing if really adventurous. .HEX have the ability to be sparse, out-of-order, and describe partial flash-lines.
๐ŸŒ
Tomeko
tomeko.net โ€บ online_tools โ€บ ascii.php
ASCII to C-like array converter
See also: bin2hex.exe for Windows and bin2hex for Linux (source code).
๐ŸŒ
GitHub
gist.github.com โ€บ xsleonard โ€บ 7341172
hex string to byte array, C ยท GitHub
I added a small check to fix that. int HexStringToBytes(const char *hexStr, unsigned char *output, unsigned int *outputLen) { size_t len = strlen(hexStr); if (len % 2 != 0) { return -1; } size_t finalLen = len / 2; *outputLen = finalLen; for (size_t inIdx = 0, outIdx = 0; outIdx < finalLen; inIdx += 2, outIdx++) { if ((hexStr[inIdx] - 48) <= 9 && (hexStr[inIdx + 1] - 48) <= 9) { goto convert; } else { if (((hexStr[inIdx] - 65) <= 5 && (hexStr[inIdx + 1] - 65) <= 5) || ((hexStr[inIdx] - 97) <= 5 && (hexStr[inIdx + 1] - 97) <= 5)) { goto convert; } else { *outputLen = 0; return -1; } } convert: output[outIdx] = (hexStr[inIdx] % 32 + 9) % 25 * 16 + (hexStr[inIdx + 1] % 32 + 9) % 25; } output[finalLen] = '\0'; return 0; }
๐ŸŒ
IncludeHelp
includehelp.com โ€บ tips โ€บ c โ€บ how-to-initialize-array-elements-with-hexadecimal-values-in-c.aspx
How to initialize array elements with hexadecimal values in C?
#include <stdio.h> int main() { //loop counter int i; //declraing integer array and //initializing with hexadecimal values int arr[]={0x1000, 0x2000, 0x10AF, 0xABCD, 0xF100}; //getting length of the array int length = sizeof(arr)/sizeof(arr[0]); //printing the elements for(i=0; i<length; i++) printf("arr[%d]: HEX: X, DEC: %d\n",i,arr[i],arr[i]); return 0; } ... arr[0]: HEX: 1000, DEC: 4096 arr[1]: HEX: 2000, DEC: 8192 arr[2]: HEX: 10AF, DEC: 4271 arr[3]: HEX: ABCD, DEC: 43981 arr[4]: HEX: F100, DEC: 61696 ... How to use Macro instead of 'Equal To' operator to reduce 'Equal To' or 'Assignment' operator confusion in C
Find elsewhere
๐ŸŒ
Hackaday
hackaday.io โ€บ project โ€บ 167711-3-chip-z80-design โ€บ log โ€บ 169747-converting-grants-hex-files-to-c-arrays
Converting Grant's Hex files to C arrays | Details | Hackaday.io
October 10, 2019 - Convert basic hex file to C array: srecord\srec_cat basic.hex -intel -o basic.c -C-Array Convert rom hex file to C array: srecord\srec_cat rom.hex -intel -o rom.c -C-Array The memory map on Grant's site: MEMORY MAPS INITIAL BOOT 0000-3FFF ROM Within the ROM...
๐ŸŒ
GitHub
github.com โ€บ AhmedYousriSobhi โ€บ Hex-To-array-txt
GitHub - AhmedYousriSobhi/Hex-To-array-txt: C code to convert Hex file to array Txt file
C code to convert Hex file to array Txt file. Contribute to AhmedYousriSobhi/Hex-To-array-txt development by creating an account on GitHub.
Author: AhmedYousriSobhi
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ reading hex values from external file into an array
Reading hex values from external file into an array : r/C_Programming
February 15, 2024 - if (fscanf(file, "%x%c", &array[i], &dummy_char) == 2 && *dummy_char == ',') should do roughly what you want. If you don't want to use that, you could also use strtoul().
๐ŸŒ
Reddit
reddit.com โ€บ r/askprogramming โ€บ storing hex values in an int array c
Storing Hex values in an int array C : r/AskProgramming
March 23, 2018 - A single hex digit ("0" through "F") is exactly four binary bits. If you know your "array" won't contain more than 8 hex digits, just keep them in a 32-bit integer (uint32_t) and use shifting and bitwise masking to access them: elem = (ar >> (index * 4)) && 0xF;
๐ŸŒ
LinuxQuestions.org
linuxquestions.org โ€บ questions โ€บ programming-9 โ€บ how-to-define-hex-character-array-in-c-668213
How to define hex character array in C?
September 7, 2008 - Hi group, I have a simple question. I want to define a hex character array in C, but I don't want to have to define the elements one at a time.
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 352381 โ€บ how-to-define-hex-character-array-in-c
algorithm pseudocode - How to define hex character array in C? | DaniWeb
Yes, that's understandable. If you want to use hexadecimal literals in your code, they must have an 0x prefix. That's how the compiler can tell the difference and set the actual value accordingly. The equivalent decimal array would be:
๐ŸŒ
Notisrac
notisrac.github.io โ€บ FileToCArray
File to C style array converter
4 weeks ago - The array declaration will contain bytes in this format. So if you have choosen "Hex (0x00)", it will give you this output: static const unsigned char awesomeimage[] = { 0x00, 0xff, 0xff }; ... This tells the converter to treat the current file as a binary, eventhough it is an image.
๐ŸŒ
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); }
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);
}
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 16464278 โ€บ convert-array-of-numbers-into-single-hex-value-in-c
Convert array of numbers into single Hex value in c - Stack Overflow
Below is the simple logic i implemented.... void DecToHex(unsigned char* dst, unsigned char* src); unsigned char digits[12] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x01,0x02,0x03}; unsigned char result[10]= {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; void main(void) { /* digits[12] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x01,0x02,0x03}; */ DecToHex(result, digits); /* result[10] : 0x1C,0xBE,0x99,0x1A,0x83,......... */ while(1); } void DecToHex(unsigned char* dst, unsigned char* src) { unsigned char tmp; unsigned char i, j=10; while(j!=0) { j -= 1; /* reinitialize for
๐ŸŒ
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 want a string, or do you just want to print 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 see aabb1277 when I use %s, not %x.