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 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