C# Tips

C# Tip Article

Convert byte array to hex string

Sometimes we need to convert byte array to a concatenated hex string. Nice thing about it is .NET already has a static class for it. Use BitConverter.ToString().

var bytes = new byte[] { 0x25, 0xA3, 0x5e, 0x75, 0x90, 0xde };

// Convert byte array to a string (concatenation)            
string str = BitConverter.ToString(bytes);
// Output: 25-A3-5E-75-90-DE

str = str.Replace("-", ""); 
// Output: 25A35E7590DE

BitConverter.ToString() concatenates each byte with dash. If no dash is needed, simply replace dash to empty string.

As a side note, we might want to convert byte array to string array. Typically we can use for loop, but probably make it simpler using LINQ.

// Convert byte array to string array            
string[] strArray = bytes.Select(p => p.ToString("x2")).ToArray();
// Output: 
// strArray[0] = 25
// strArray[1] = a3
// strArray[2] = 5e
// strArray[3] = 75
// strArray[4] = 90
// strArray[5] = de

Each array element has lowercase hex string. But you can use .ToString("X2") to get uppercase hex string.