How to: Convert ASCII to HEX and HEX to ASCII

By Peter Bromberg

Two convenient methods in C# to make ASCII to Hexadecimal conversions.

 public string HEX2ASCII( string hex)
       {
           string res = String.Empty ;
           for (int a = 0; a <hex.Length ; a = a + 2)
           {
               string Char2Convert = hex.Substring(a, 2);
               int n = Convert.ToInt32(Char2Convert, 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();
        }
 

How to: Convert ASCII to HEX and HEX to ASCII  (10592 Views)