Question

I am looking for a smart way to convert a string of hex-byte-values into a string of 'real text' (ASCII Characters).

For example I have the word "Hello" written in Hexadecimal ASCII: 48 45 4C 4C 4F. And using some method I want to receive the ASCII text of it (in this case "Hello").

// I have this string (example: "Hello") and want to convert it to "Hello".
string strHexa = "48454C4C4F";

// I want to convert the strHexa to an ASCII string.
string strResult = ConvertToASCII(strHexa);

I am sure there is a framework method. If this is not the case of course I could implement my own method.

Thanks!

Was it helpful?

Solution

var str = Encoding.UTF8.GetString(SoapHexBinary.Parse("48454C4C4F").Value); //HELLO

PS: SoapHexBinary is in System.Runtime.Remoting.Metadata.W3cXsd2001 namespace

OTHER TIPS

I am sure there is a framework method.

A a single framework method: No.

However the second part of this: converting a byte array containing ASCII encoded text into a .NET string (which is UTF-16 encoded Unicode) does exist: System.Text.ASCIIEncoding and specifically the method GetString:

string result = ASCIIEncoding.GetString(byteArray);

The First part is easy enough to do yourself: take two hex digits at a time, parse as hex and cast to a byte to store in the array. Seomthing like:

byte[] HexStringToByteArray(string input) {
  Debug.Assert(input.Length % 2 == 0, "Must have two digits per byte");
  var res = new byte[input.Length/2];

  for (var i = 0; i < input.Length/2; i++) {
    var h = input.Substring(i*2, 2);
    res[i] = Convert.ToByte(h, 16);
  }

  return res;
}

Edit: Note: L.B.'s answer identifies a method in .NET that will do the first part more easily: this is a better approach that writing it yourself (while in a, perhaps, obscure namespace it is implemented in mscorlib rather than needing an additional reference).

  StringBuilder sb = new StringBuilder();  
  for (int i = 0; i < hexStr.Length; i += 2)
    {
        string hs = hexStr.Substring(i, 2);
        sb.Append(Convert.ToByte(hs, 16));
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top