简体   繁体   中英

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.

Example input string:

std:string strInput = "FF2139FF"

Example output string should be "ÿ.9ÿ" in the text file.

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? 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.

Try for example XVI 32 hex editor

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. It can show the correct letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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