How To Convert From String To Hex To String

I was writing some code that required that all text be hex encoded and was appalled that the .NET Framework didn't have a Convert method for doing hex, so I had to write my own.  Converting text to hex is quite simple using the method below:

public static String ConvertToHex(String asciiString) { StringBuilder sb = new StringBuilder(asciiString.Length); foreach (char c in asciiString) { int intVal = c; sb.Append(String.Format("{0:x2}", (uint)System.Convert.ToUInt32(intVal.ToString()))); } return sb.ToString(); }
It's pretty straight forward, all you do is take each char in the String, cast it to an int, and use a Formatter to convert it into a String again. Converting from hex to String is a little more involving, but easy nonetheless:
        public static String ConvertFromHex(String hex) 
         { 
             String[] hexArray = new String[hex.Length / 2]; 

             if (hex.Length % 2 != 0) 
             { 
                 throw new FormatException("The hex string passed in was not a valid hex string."); 
             } 

             for (int i = 0; i < hexArray.Length; i++) 
             { 
                 hexArray[i] = hex.Substring(i*2, 2); 
             } 

             StringBuilder asciiString = new StringBuilder(hex.Length / 2); 

             foreach (String s in hexArray) 
             { 
                 asciiString.Append((char)Convert.ToInt32(s, 16)); 
             } 

             return asciiString.ToString(); 
         }

You have to chop up those hex numbers in pairs of two, then one by one, convert to int and cast to a char, then concatenate back into a String representation.

Posted on Nov 21
Written by Wayne Hartman