23 February 2011

.NET - String to hexadecimal and vice versa

The following functions encode a string to hexadecimal form and the other way round. I use this method to avoid encoding issues in data files:
protected string EncodeStrToHex(string str) {
  if (string.IsNullOrEmpty(str))
    return str;
  byte[] chars = Encoding.UTF8.GetBytes(str);
  StringBuilder result = new StringBuilder(chars.Length);
  foreach (byte c in chars) {
    result.Append(c.ToString("X2"));
  }
  return result.ToString();
}

protected string EncodeHexToStr(string hex) {
  if (string.IsNullOrEmpty(hex))
    return hex;
  byte[] chars = new byte[hex.Length / 2];
  string c = string.Empty;
  for (int i = 0, j = 0; i < chars.Length; i++, j += 2) {
    c = new string(new char[] { hex[j], hex[j + 1] });
    chars[i] = byte.Parse(c, NumberStyles.HexNumber);
  }
  return Encoding.UTF8.GetString(chars);
}

No comments:

Post a Comment