Hex convertion to string in C#

I have a string variable in Hex format which I need to convert to a standard ASCII string ; eg "48656C6C6F20576F726C64" should convert to "Hello World". I can't seem to find anything in the help files which actually helps with what should be a fairly common requirement. If anyone can throw light on this (and indeed the reverse conversion) I would be very grateful.

Answer this question

Hex convertion to string in C#

  • Alexandre Luzes

    Yes, well I have it working, if a little longwindedly!! here is the code

    private string HexAsciiConvert(string hex)

    {

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i <= hex.Length - 2; i += 2)

    {

    sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hex.Substring(i, 2),

    System.Globalization.NumberStyles.HexNumber))));

    }

    return sb.ToString();

    }

    However, I am sure that there must be a simpler way than a double conversion!


  • UI Freak

    I don't know if there is a better way to do it, but I would use Int32.Parse(string, NumberStyle.HexNumber) to convert each two characters to the equivalent ascii code, from which you can build the new string.
  • dcarlson

    Yes I suppose so. It's just so irritating that, with so much work that has supposedly gone into VS2005 C#, they can't even provide a simple conversion like this in a single shot. I'm sure that I can't be the only person in the world that needs to get the ascii equivalent to a hex string. It used to be so easy in VB!!!

    Thanks for all the help anyway.


  • Alan Chua

    I doubt it, because conceptually you need to do a "double conversion". If the framework provided a method for this, that method would essentially have to perform the same steps.
  • kosar1349

    Sounds good to me. I'll give it a try
  • Hex convertion to string in C#