How to Convert byte array to hex string in C#

By FoxLearn 10/29/2024 2:43:28 PM   127
To convert a byte array to a hex string in C#, you can use the BitConverter class or manually format each byte.

To convert a byte array to a concatenated hex string in .NET, you can use the static BitConverter.ToString() method. This simplifies the process by handling the conversion for you, making it easy to get the desired hex format.

For example:

byte[] byteArray = { 0x01, 0xA0, 0xFF, 0x10 };
string hexString = BitConverter.ToString(byteArray).Replace("-", "").ToLower();
Console.WriteLine(hexString); // Output: 01a0ff10

The BitConverter.ToString() concatenates each byte with dashes. To remove the dashes and get a continuous hex string, you can replace them with an empty string.

If you prefer to format the string manually, you can use StringBuilder:

byte[] byteArray = { 0x01, 0xA0, 0xFF, 0x10 };
var hexStringBuilder = new StringBuilder();

foreach (byte b in byteArray)
    hexStringBuilder.AppendFormat("{0:x2}", b);

string hexString = hexStringBuilder.ToString();
Console.WriteLine(hexString); // Output: 01a0ff10

To convert a byte array to a string array, you can use a for loop, but a simpler approach is to utilize LINQ for more concise code.

string[] strArray = byteArray.Select(p => p.ToString("x2")).ToArray();

Each element of the array produces a lowercase hex string by default. However, you can use .ToString("X2") to obtain an uppercase hex string.