Search code examples
c++builder

How to convert a unicode hex string into its ASCII equivalent


I hope everything is going well.

I have this unicodestring:

353135313531353135313531

And I want to transform it into another unicodestring with this content:

515151515151

In other words, convert a hex representation into its ASCII interpretation.

It is very straightforward to do this in C, but the idea is to work with C++ Builder.

This is what I have been trying to do:

String hex_to_ascii(const String& hex_str) {
    String ascii_str = "";
    for (int i = 1; i <= hex_str.Length(); i += 2) {
        String hex_char = hex_str.SubString(i, 2);
        int ascii_char = hex_char.ToInt();
        // ascii_str += String().sprintf(_D("%c"), ascii_char);
        ascii_str.Insert(ascii_char, ascii_str.Length() + 1);
    }
    return ascii_str;

But no luck so far.

I know there is a method called ToHex I've been trying to search for documentation about it because it's related to what I am trying to do, so probably the library that has this method has also something close to what I need.

If you know how to do this or where can I read about the ToHex method, please let me know. Thank you for reading.


Solution

  • The code you have is very close, it just needs some minor tweaks.

    Most importantly, String::ToInt() WILL NOT decode hex, like you are expecting. It will convert "35" to an integer with a value of decimal 35 (NOT hex 0x35, decimal 53), and will convert "31" to an integer with a value of decimal 31 (NOT hex 0x31, decimal 49), etc.

    You need to instead use Sysutils::StrToInt() with a 0x hex prefix prepended to the string value.

    Try this:

    String hex_to_ascii(const String& hex_str) {
        String ascii_str;
        for (int i = 1; i <= hex_str.Length(); i += 2) {
            String hex_char = _D("0x") + hex_str.SubString(i, 2);
            int ascii_char = StrToInt(hex_char);
            ascii_str += static_cast<Char>(ascii_char);
        }
        return ascii_str;
    }
    

    Alternatively, you can use HexToBin() to decode the hex into a byte array, and then construct a UnicodeString from those bytes, eg:

    String hex_to_ascii(const String& hex_str) {
        TBytes bytes;
        bytes.Length = hex_str.Length() / 2;
        HexToBin(hex_str.c_str(), &bytes[0], bytes.Length);
        return String((char*)&bytes[0], bytes.Length);
        // Alternatively:
        // return TEncoding::Default.GetString(bytes);
    }