Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to convert a String of hex to ASCII, using this:

public void ConvertHex(String hexString)
{
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < hexString.Length; i += 2)
    {
        String hs = hexString.Substring(i, i + 2);
        System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
    }
    String ascii = sb.ToString();
    MessageBox.Show(ascii);
}

but I get an out or bounds exception, I'm sure its a glaring error but other code I have tried does not work either. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
953 views
Welcome To Ask or Share your Answers For Others

1 Answer

This code will convert the hex string into ASCII, you can copy paste this into a class and use it without instancing

public static string ConvertHex(String hexString)
{
    try
    {
        string ascii = string.Empty;

        for (int i = 0; i < hexString.Length; i += 2)
        {
            String hs = string.Empty;

            hs   = hexString.Substring(i,2);
            uint decval =   System.Convert.ToUInt32(hs, 16);
            char character = System.Convert.ToChar(decval);
            ascii += character;

        }

        return ascii;
    }
    catch (Exception ex) { Console.WriteLine(ex.Message); }

    return string.Empty;
}

Notes

2 = the no. of hexString chars used to represent an ASCII character.

System.Convert.ToUInt32(hs, 16) = "convert the base 16 hex substrings to an unsigned 32 bit int"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...