Monday, August 25, 2008

How to Convert between byte and Hex string

Please see the function below:




/// Convert a string of hex digits (ex: E4 CA B2) to a byte array.
/// The string containing the hex digits (with or without spaces).
/// Returns an array of bytes.
private byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}

/// Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)
/// The array of bytes to be translated into a string of hex digits.
/// Returns a well formatted string of hex digits with spacing.
private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}


No comments: