Convert Hex to Readable String and Readable Text to Hex

If you ever need to convert Hex data to readable strings or the reverse, try the following methods:

 
private static readonly  char[] HexChars = "0123456789ABCDEF".ToCharArray();
 
private static string ConvertToHex(string ascii)
{
if (ascii == null) return null;
if (ascii == "") return "";
 
byte[] bytes = Encoding.UTF8.GetBytes(ascii);
 
StringBuilder converted = new StringBuilder(bytes.Length * 2);
 
foreach (byte b in bytes)
{
converted.Append(HexChars[b >> 4]);
converted.Append(HexChars[b & 0xf]);
}
 
return converted.ToString();
}
 
private static string ConvertFromHex(string hex)
{
if (hex == null) return null;
if (hex == "") return "";
if (hex.Length % 2 != 0)
throw new ApplicationException("hex string length should be divisble by 2: " + hex);
 
byte[] bytes = new byte[hex.Length / 2];
 
for (int i = 0; i < bytes.Length; i++)
bytes[i] = byte.Parse(hex[2 * i] + "" + hex[2 * i + 1], NumberStyles.HexNumber);
 
string converted = Encoding.UTF8.GetString(bytes);
 
if (converted[converted.Length - 1] == '\0')
converted = converted.Remove(converted.Length - 1, 1);
 
return converted;
}

I have found this is very useful for parsing binary data from Active Directory sources such as “csvde”.

Hope this helps you out! Let me know if you know of a better/faster method – it is always appreciated.

This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *