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...
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With