c++ - 将文件中的十六进制数转换为 ASCII

标签 c++ c hex ascii

我有一个文件,我必须使用 fopen 打开它。现在文件的问题是它是一个十六进制文件,所以当我打开它时,我看到十六进制数字,例如 RG 是 5247。现在当我使用 (fgets(line, sizeof(line), fd)

line[0] is 5
line[1] is 2
line[2] is 4
line[4] is 7. 

52char R 的十六进制,47char G 的十六进制。我想得到那个。我知道我可以使用查找表,这会起作用,但我一直在寻找更多不同的解决方案。已经尝试了很多但无济于事。

请帮忙!!

最佳答案

  • 将十六进制转换为整数
  • 将结果转换为 char,类似于 char res = (char)intValue;

代码:

// this works if the string chars are only  0-9, A-F 
// because of implemented mapping in `hex_to_int`

int hex_to_int(char c){
        int first = c / 16 - 3;//    1st is dec 48 = char 0
        int second = c % 16; //      10 in 1st16  5 in 2nd 16
        // decimal code of ascii char 0-9:48-57  A-E: 65-69
        // omit dec 58-64:  :,;,<,=,>,?,@
        // map first or second 16 range to 0-9 or 10-15
        int result = first*10 + second; 
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

输出:

Hello;

RUN SUCCESSFUL (total time: 59ms)

关于c++ - 将文件中的十六进制数转换为 ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18431394/

相关文章:

python - 删除字符串python中的utf-8文字

swift 3 : Negative Int to hexadecimal

c++ - 如何在 C++ 中制作一个无需复制即可返回静态或自动存储对象的函数?

有人可以解释这个 'typedef' 的含义吗?

c - printf 不工作(指针)

c - 如何使结构体指向不同的字符串?

c# - 将十六进制字符串转换为其在 C# 中的数值

C++ 在给定位置寻找一个 std::string::iterator

c++ - std::getline 在一个项目中编译正常,但在另一个项目中编译不正常

c++ - OpenGL GL_TEXTURE1 不显示