#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char *string2bin_ar[] = {
        "0000", // 0
        "0001", // 1
        "0010", // 2
        "0011", // 3
        "0100", // 4
        "0101", // 5
        "0110", // 6
        "0111", // 7
        "1000", // 8
        "1001", // 9
        "1010", // A
        "1011", // B
        "1100", // C
        "1101", // D
        "1110", // E
        "1111", // F
        };


char *
string2binstr(char *hexstring) {
        size_t len = strlen(hexstring);
        size_t idx = 0;
        unsigned char no;
        char *out;
        if (!len) {
                fprintf(stderr, "string2bin: no input data");
                return NULL;
        }
        /* string can't be less then 32 bits (chars in sample)
         * 32 (minimum length) / 4 (hex chunk length) = 8 (number of hex chuncks) */
        out = calloc(1, (len < 8 ? 32 : len * 4 ) + 1);
        if (!out) {
                fprintf(stderr, "string2bin: no enough memory\n");
                return NULL;
        }
        out[len * 4] = '\0';
        for (; idx < len; idx++) {
                no = (unsigned char)hexstring[idx];
                if (no >= '0' && no <= '9')
                        no -= '0';
                else if (no >= 'A' && no <= 'F')
                        no -= ('A' - 10);
                else if (no >= 'a' && no <= 'f')
                        no -= ('a' - 10);
                else no = 0;
                memcpy(&out[idx * 4], string2bin_ar[no], 4);
        }
        /* fill missing bits (bytes) */
        if (idx < 8)
                memset(&out[idx * 4], '0', 32 - idx * 4);
        return out;
}

int main(int argc, char *argv[])
{
	printf("%s\n", string2binstr("FF"));
	
	return 0;
}