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

我有一个十六进制值的文本文件.现在我需要将十六进制值转换为二进制,并需要将其保存在另一个文件中.
但我不知道如何将十六进制值转换为二进制字符串!
请帮忙…
最佳答案
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

作为替代方案(假设没有像“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

转载注明原文:如何在C中将十六进制字符串转换为二进制字符串 - 代码日志