Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a hexadecimal string to a binary string in C

Tags:

c

hex

binary

I have a text file with hexadecimal values. Now I need to convert the hexadecimal value to binary and need to save it on another file. But I don't know how to convert the hexadecimal value to a binary string! Please help...

like image 520
Midhun MP Avatar asked Dec 18 '11 11:12

Midhun MP


2 Answers

It's quite easy, really, because the translation goes digit-by-digit.

0 - 0000
1 - 0001
2 - 0010
3 - 0011
4 - 0100
5 - 0101
6 - 0110
7 - 0111
8 - 1000
9 - 1001
A - 1010
B - 1011
C - 1100
D - 1101
E - 1110
F - 1111

So, for example, the hex number FE2F8 will be 11111110001011111000 in binary

like image 131
Armen Tsirunyan Avatar answered Sep 19 '22 16:09

Armen Tsirunyan


const char input[] = "..."; // the value to be converted
char res[9]; // the length of the output string has to be n+1 where n is the number of binary digits to show, in this case 8
res[8] = '\0';
int t = 128; // set this to s^(n-1) where n is the number of binary digits to show, in this case 8
int v = strtol(input, 0, 16); // convert the hex value to a number

while(t) // loop till we're done
{
    strcat(res, t < v ? "1" : "0");
    if(t < v)
        v -= t;
    t /= 2;
}
// res now contains the binary representation of the number

As an alternative (this assumes there's no prefix like in "0x3A"):

const char binary[16][5] = {"0000", "0001", "0010", "0011", "0100", ...};
const char digits = "0123456789abcdef";

const char input[] = "..." // input value
char res[1024];
res[0] = '\0';
int p = 0;

while(input[p])
{
    const char *v = strchr(digits, tolower(input[p++]));
    if (v)
        strcat(res, binary[v - digits]);
}
// res now contains the binary representation of the number
like image 33
Mario Avatar answered Sep 18 '22 16:09

Mario