如何将十六进制字符串转换在C二进制字符串 [英] How to convert a hexadecimal string to a binary string in C
本文介绍了如何将十六进制字符串转换在C二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有十六进制值的文本文件。现在我需要的十六进制值转换为二进制,并需要将其保存在另一个文件。
但我不知道如何将十六进制值转换为二进制字符串!
请帮助...
解决方案
为const char输入[] =...; //值被转换
焦炭资源[9]; //输出字符串的长度必须的n + 1,其中n是二进制数字的个数来显示,在这种情况下,8
RES [8] ='\\ 0';
INT T = 128; //设置此为s ^(N-1)其中n是二进制数字的个数来显示,在这种情况下,8
INT V =与strtol(输入,0,16); //十六进制值转换为数字而(T)//循环,直到我们就大功告成了
{
strcat的(资源,T< V1:0);
如果(T< 5)
v - 输出= T;
T / = 2;
}
//水库现在包含数的二进制重新presentation
作为替代方案(假定有一个在0x3A
没有preFIX等):
常量字符二进制[16] [5] = {0000,0001,0010,0011,0100,...};
为const char位数=0123456789ABCDEF;为const char输入[] =...//输入值
焦炭资源[1024];
RES [0] ='\\ 0';
INT p值= 0;而(输入[P])
{
为const char * V =和strchr(数字,tolower的(输入[P ++]));
如果(v)的
的strcat(水库,二进制[V [0]);
}
//水库现在包含数的二进制重新presentation
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...
解决方案
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[0]]);
}
// res now contains the binary representation of the number
这篇关于如何将十六进制字符串转换在C二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文