如何在C中将十六进制字符串转换为二进制字符串

Mid*_* MP 5 c binary hex

我有一个十六进制值的文本文件.现在我需要将十六进制值转换为二进制,并需要将其保存在另一个文件中.但我不知道如何将十六进制值转换为二进制字符串!请帮忙...

Arm*_*yan 9

这真的非常简单,因为翻译是逐位的.

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
Run Code Online (Sandbox Code Playgroud)

因此,例如,十六进制数FE2F8将是11111110001011111000二进制的


Mar*_*rio 5

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
Run Code Online (Sandbox Code Playgroud)

作为替代方案(假设没有像 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
Run Code Online (Sandbox Code Playgroud)