How to convert a hex to a byte array in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>

#define HEXSIZE 8

enum { ARRAYSIZE = HEXSIZE / 2 };

void hex_to_byte_array(const char hex[], unsigned char byteArray[]) {
    int temp;

    for (int i = 0; i < ARRAYSIZE; ++i) {
        sscanf(hex + 2 * i, "%2x", &temp);
        byteArray[i] = temp;
    }
}

int main() {
    const char hex[HEXSIZE] = "1E2D3E4F";
    unsigned char byteArray[ARRAYSIZE] = "";
    
    hex_to_byte_array(hex, byteArray);

    for (size_t i = 0; i < 4; ++i) {
        printf("%02X ", byteArray[i]);
    }

    return 0;
}



/*
run:

1E 2D 3E 4F 

*/


 



answered Feb 14, 2025 by avibootz
edited Feb 14, 2025 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

#define HEXSIZE 8

enum { ARRAYSIZE = HEXSIZE / 2 };

void hex_to_byte_array(const char hex[], unsigned char byteArray[]) {
    for (int i = 0; i < ARRAYSIZE; ++i) {
        sscanf(hex, "%2hhx", &byteArray[i]);
        hex += 2;
    }
}

int main() {
    const char hex[HEXSIZE] = "1A2D3E4F";
    unsigned char byteArray[ARRAYSIZE] = "";
    
    hex_to_byte_array(hex, byteArray);

    for (size_t i = 0; i < 4; ++i) {
        printf("%02X ", byteArray[i]);
    }

    return 0;
}



/*
run:

1A 2D 3E 4F 

*/


 



answered Feb 14, 2025 by avibootz

Related questions

1 answer 218 views
2 answers 246 views
1 answer 174 views
174 views asked Feb 14, 2025 by avibootz
1 answer 187 views
...