简体   繁体   中英

C# - Trying to convert string (with HEX) to display extended ASCII chars in TextBox

I am trying to take a string with hex FFFFFFFF7DA98035 and display its extended ASCII characters in a TextBox in my program. I am having problems with 80 as its -128 and displays nothing.

Visual Studio compiles without errors, but throws an exception when it parses the string.

private static string ConvertHextoAscii(string HexString)
{
    byte[] data = new byte[HexString.Length / 2];

    for (int i = 0; i < HexString.Length - 1; i += 2)
    {
        data[i / 2] = byte.Parse(HexString.Substring(i, 2));
    }

    return Encoding.GetEncoding("Windows-1252").GetString(data);
}

Any help would be appreciated.

byte.Parse is expecting a string that contains an integer (in decimal). However, HexString.Substring(i, 2) will return a hex number (as a string).

Do the following to instruct byte.Parse to expect a hex number:

data[i / 2] = byte.Parse(HexString.Substring(i, 2), NumberStyles.HexNumber);

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