简体   繁体   English

C++ 将 HexString 转换为扩展的 Ascii 代码在文本文件中不显示正确的 ascii 代码

[英]C++ convert HexString to extended Ascii code not show correct ascii code in the text file

How to convert hex string to extended ascii code symbol code and write the converted codes to the text file.如何将十六进制字符串转换为扩展的 ascii 代码符号代码并将转换后的代码写入文本文件。

Example input string:示例输入字符串:

std:string strInput = "FF2139FF"标准:字符串strInput =“FF2139FF”

Example output string should be "ÿ.9ÿ" in the text file.示例 output 字符串在文本文件中应为“ÿ.9ÿ”。

I tried to write the program as below to write to a text file.我尝试编写如下程序以写入文本文件。

#include <string>
using namespace std;

string ConvertHexStringToAsciiString(string sInputHexString, int step)
{
    int len = sInputHexString.length();
    string sOutputAsciiString;
    for (int i = 0; i < len; i += step)
    {
        string byte = sInputHexString.substr(i, step);
        char chr = (char)(int)strtol(byte.c_str(), nullptr, 16);
        sOutputAsciiString.push_back(chr);
    }
    return sOutputAsciiString;
}

void main()
{
    string sInputHexString = "FF2139FF";

    string sOutputAsciiString = "";
    sOutputAsciiString = ConvertHexStringToAsciiString(sInputHexString, 2);

    const char* sFileName = "E:\\MyProgramDev\\Convert_HexString_To_AsciiCode\\Convert_HexString_To_AsciiCode\\TestFolder\\1.txt";
    FILE* file = fopen(sFileName, "wt");
    if (nullptr != file)
    {
        fputs(sOutputAsciiString.c_str(), file);
        fclose(file);
    }
}

It seems working but when I open the text file 1.txt with notepad, I cannot see the ÿ and only.9 displayed?它似乎工作,但是当我用记事本打开文本文件 1.txt 时,我看不到 ÿ 和 only.9 显示? I am not sure how to display it correctly using notepad or my code is wrong?我不确定如何使用记事本正确显示它或我的代码错误?

Thanks.谢谢。

Use better notepad - or even better, any hexeditor to view result.使用更好的记事本 - 甚至更好的任何 hexeditor 来查看结果。

Try for example XVI 32 hex editor尝试例如XVI 32 十六进制编辑器

I found a way to do thing, Split this HexString FF to two BYTE(unsigned char) "F" and "F", and then construct together and convert to decimal.我找到了一种方法,将这个 HexString FF 拆分为两个 BYTE(unsigned char) "F" 和 "F",然后一起构造并转换为十进制。 It can show the correct letter.它可以显示正确的字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM