Posted by: Praveen | September 25, 2008

Sample C# code to convert Hexadecimal String to ASCII

The following C# code sample can be used for converting a Hexadecimal String(hex string) to ASCII.


private string HexString2Ascii(string hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= hexString.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
return sb.ToString();
}


Responses

  1. Muito obrigado!

  2. Your Welcome!

  3. hi, would there be a better alternative other than stringbuilder? cos my hex string is very very very long. it would be best if it can build an unlimited amount.

  4. hey it’s okay. the problem doesn’t lie with the stringbuilder. thanks for the code! :)

  5. Hi,i need to convert the data “7820 6a75 6d70 6564 206f 7665 7220″ into ascii using c# ,how is it done, can anyone help,please.

  6. thanks a lot

  7. This might cause problems if quotes itself (or some other special characters) are part of the string. A better way would be using bytes array and then using encoding to get string. For example i ran into an issue where this was the ascii result “I”ÊôL” but the hex value of 4994CAF44C would not translate into it using stringbuilder. Here’s my solution. Please let me know what you think. thx

    private static string HexString2Ascii(string hexString)
    {
    byte[] tmp;
    int j = 0;
    tmp = new byte[(hexString.Length)/2];
    for (int i = 0; i <= hexString.Length – 2; i += 2)
    {
    tmp[j] =(byte)Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));

    j++;
    }
    return Encoding.GetEncoding(1252).GetString(tmp);
    }


Leave a response

Your response:

Categories