How to convert Byte Array to Hexadecimal String, and Hexadecimal String to Byte Array?

This is a very common question over the Internet and the question among the developers, but it very difficult to find an answer that neatly explains how you can convert a byte array to a hexadecimal string, and vice versa. Here I am explaining How to convert Byte Array to Hexadecimal String, and Hexadecimal String to Byte Array?

Here I am explaining two ways of how to achieve this .
method 1

public static string ConvertByteArrayToString(byte[] ba)
{
StringBuilder strhex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
strhex.AppendFormat("{0:x2}", b);
return strhex.ToString();
}

method 2:

public static string ConvertByteArrayToString(byte[] ba)
{
string strhex = BitConverter.ToString(ba);
return strhex.Replace("-","");
}

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

The reverse conversion would go like this:

public static byte[] ConvertStringToByteArray(String strhex)
{
int NumberChars = strhex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(strhex.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.Just produced a high performance lookup table based implementation. Its safe variant is about 30% faster than the current leader on my CPU. The unsafe variants are even faster.

Leave a Reply

Your email address will not be published. Required fields are marked *