Tuesday, 17 May 2016

c# - How do you convert a byte array to a hexadecimal string, and vice versa?



How can you convert a byte array to a hexadecimal string, and vice versa?


Answer



Either:



public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)

hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}


or:



public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-","");

}


There are even more variants of doing it, for example here.



The reverse conversion would go like this:



public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;

byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}





Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...