Convert String to Hex and Hex to String in .NET

By Miguel Santos

This faq will show you how to convert string to hexadecimal string and viceversa. It takes in accountthe string encoding because if the original string contains unicode characters (like RC4 strings) the typical solution (targeting Ascii strings) will fail.

Here is the source code in C#
a) Convert String to Hex

         public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
        {
             Byte[] stringBytes = encoding.GetBytes(input);
           StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
            foreach (byte b in stringBytes)
             {
                 sbBytes.AppendFormat("{0:X2}", b);
            }
            return sbBytes.ToString();
        }

b) Convert Hex to String

         public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
        {
             int numberChars = hexInput.Length;
            byte[] bytes = new byte[numberChars / 2];
             for (int i = 0; i < numberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
             }
             return encoding.GetString(bytes);
        }

Sample usage code

   string testString = "MIKA@?&^";
   string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);
   string normal = ConvertHexToString(hex, System.Text.Encoding.Unicode);
   Debug.Assert(testString.CompareTo(normal) == 0, "They are not identical");

For example, you use Encoding.Unicode for RC4 or Encoding.ASCII for simple text .

The sample code is in C# but can translated to VB.NET very easily, for example the sample usage code is:
   Dim testString As String = "MIKA@?&^"
   Dim hex As String = ConvertStringToHex(testString, System.Text.Encoding.Unicode)
   Dim normal As String = ConvertHexToString(hex, System.Text.Encoding.Unicode)
   Debug.Assert(testString.CompareTo(normal) == 0, "They are not identical")

For additional information check:
http://msdn.microsoft.com/en-us/library/bb311038.aspx

Convert String to Hex and Hex to String in .NET  (27087 Views)