Google+ Peter Bromberg's .NET Blog | CONVERSION

Peter Bromberg's .NET Blog All Things Programming

Convert ASCII to Hexadecimal and Hexadecimal to ASCII

6. August 2013 08:12 by admin in CONVERSION, C#, General

 

Here a couple of utility methods in C# to make ASCII to Hexadecimal conversions.

 
 public string HexToAscii( string hex)
{
string res = String.Empty ;for (int a = 0; a <hex.Length ; a = a + 2)
{
string CharToConvert = hex.Substring(a, 2);int n = Convert.ToInt32(CharToConvert, 16);char c = (char)n;
res += c.ToString();
}
return res;
} 
public string AsciiToHex(string ascii)
{
StringBuilder sb = new StringBuilder();byte[] inputBytes = Encoding.UTF8.GetBytes(ascii);foreach (byte b in inputBytes)
{
sb.Append(string.Format("{0:x2}", b));
}
return sb.ToString();
}