Problem converting HEX string to ASCII

Wismeryl

New member
Joined
Sep 24, 2014
Messages
2
Programming Experience
3-5
Hi all, i have this string in HEX: 00024944554E49563130434800A0 and need to convert in ASCII.

I have tried to use the following solution, but the encoding of the last parte of the string is incorrect "00A0" after the conversion in ASCII (and converted again to be sure of the date transmitted) became "003F", probably is an Encode problem, but i dont know how and where use it with success.


public static string HextoAscii(string HexString)
{
string asciiString = "";
for (int i = 0; i < HexString.Length; i += 2)
{
if (HexString.Length >= i + 2)
{
String hs = HexString.Substring(i, 2);
asciiString = asciiString + System.Convert.ToChar(System.Convert.ToUInt32(HexString.Substring(i, 2), 16)).ToString();
}
}
return asciiString;
}

Thank you very much for your help :)
 
retry ;)

// edit
As my previous reply with incorrect formatting was removed, this reply did make sense.
I've passed your input string to your method and below is the result.
// end edit

C#:
        [0x00000000]    0x0000 '\0'    char
        [0x00000001]    0x0002 ''    char
        [0x00000002]    0x0049 'I'    char
        [0x00000003]    0x0044 'D'    char
        [0x00000004]    0x0055 'U'    char
        [0x00000005]    0x004e 'N'    char
        [0x00000006]    0x0049 'I'    char
        [0x00000007]    0x0056 'V'    char
        [0x00000008]    0x0031 '1'    char
        [0x00000009]    0x0030 '0'    char
        [0x0000000a]    0x0043 'C'    char
        [0x0000000b]    0x0048 'H'    char
        [0x0000000c]    0x0000 '\0'    char
        [0x0000000d]    0x00a0 ' '    char
Where is the 3F??
 
Last edited:
I send my original string to a client that send me (only for test) it again to me, when the string come back from the client i can see that the last part "00A0" is now "003F" probably for the encoding page used from the method that i posted before. If was possible to chose my enconding inside that method probably i have the solution, but i have no idea how.
 
Have you checked what you get back from the client? I assume that this is TCP/IP or serial comms and you receive a byte array (which is not a string); have you checked that byte array with the debugger? Does that byte array contain 3F? Or does that still contain A0? And when you convert that to a string, it becomes 3F?

I can reproduce the 3F when I convert a byte array.

            byte[] ba = { 0x00, 0x02, 0x49, 0x44, 0x55, 0x4E, 0x49, 0x56, 0x31, 0x30, 0x43, 0x48, 0x00, 0xA0 };
            string bas = System.Text.Encoding.ASCII.GetString(ba);
            char[] ca = bas.ToCharArray();
            bas = System.Text.Encoding.UTF7.GetString(ba);
            ca = bas.ToCharArray();

The first conversion to character array contains the 3F, the second one does contain A0. so your problem might be the receiving end and not the code that you showed.
 
Back
Top Bottom