如何在C中将十六进制字符串转换为二进制字符串 [英] How to convert a hexadecimal string to a binary string in C

查看:24
本文介绍了如何在C中将十六进制字符串转换为二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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] = '';
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" 中的前缀):

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] = '';
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中将十六进制字符串转换为二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆