HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayyouhowvicebyteandversaconverthexadecimalstring

Problem

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

Solution

You can use Convert.ToHexString starting with .NET 5.

There's also a method for the reverse operation: Convert.FromHexString.

For older versions of .NET you can either use:
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

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`.

Context

Stack Overflow Q#311165, score: 1748

Revisions (0)

No revisions yet.