Here is the sample program to convert String to Hex and Hex to String in CSharp (C#).
String to Hex:
- public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
- {
- Byte[] stringBytes = encoding.GetBytes(input);
- StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
- foreach (byte b in stringBytes)
- {
- sbBytes.AppendFormat("{0:X2}", b);
- }
- return sbBytes.ToString();
- }
Hex to String:
- public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
- {
- int numberChars = hexInput.Length;
- byte[] bytes = new byte[numberChars / 2];
- for (int i = 0; i < numberChars; i += 2)
- {
- bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
- }
- return encoding.GetString(bytes);
- }
No comments:
Post a Comment