I am trying to convert a hexadecimal character array to a binary array (unsigned char) that I can use in crypto functions using Cryptlib or OpenSSL. Basically I have a Hex representation of a key like (02726d40f378e716981c4321d60ba3a3) which as a character array is 32 characters but as a binary array should be 16 bytes.

The character array is being read in from a file, how can I convert it to its binary representation as an unsigned char array?


Recommended Answers

All 2 Replies

fscanf can read 2 digit hex numbers:

#include <stdio.h>

int main()
    unsigned char binary[16] = {0};
    unsigned int hex;
    int x, y;

    for (x = 0; x < 16 && fscanf(stdin, "%2x", &hex) == 1; ++x)
        binary[x] = (unsigned char)hex;

    for (y = 0; y < x; ++y) printf("%x\n", binary[y]);

    return 0;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.