Thursday, December 1, 2016

Sample Program to Convert String to Hex and Hex to String in CSharp (C#)

Here is the sample program to convert String to Hex and Hex to String in CSharp (C#).


String to Hex:
  1. public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
  2. {
  3. Byte[] stringBytes = encoding.GetBytes(input);
  4. StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
  5.  
  6. foreach (byte b in stringBytes)
  7. {
  8. sbBytes.AppendFormat("{0:X2}", b);
  9. }
  10.  
  11. return sbBytes.ToString();
  12. }

Hex to String:
  1. public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
  2. {
  3. int numberChars = hexInput.Length;
  4. byte[] bytes = new byte[numberChars / 2];
  5.  
  6. for (int i = 0; i < numberChars; i += 2)
  7. {
  8. bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
  9. }
  10.  
  11. return encoding.GetString(bytes);
  12. }

No comments:

Post a Comment