Mastering Byte Array and Hex String Conversions in .NET
.NET developers frequently encounter the need to convert between byte arrays and hexadecimal strings. This guide explores efficient methods for these conversions.
Converting Byte Arrays to Hex Strings
From .NET 5 onwards, Convert.ToHexString
offers the simplest and most efficient solution:
string hexString = Convert.ToHexString(byteArray);
For older .NET frameworks, consider these alternatives:
hexString = ByteArrayToHex(byteArray);
where ByteArrayToHex
is defined as:
public static string ByteArrayToHex(byte[] ba) { StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString(); }
Another viable option, though potentially less efficient:
hexString = BitConverter.ToString(byteArray).Replace("-", "");
Converting Hex Strings to Byte Arrays
The reverse conversion is equally important:
byte[] byteArray = HexToStringArray(hexString);
The HexToStringArray
function can be implemented as:
public static byte[] HexToStringArray(string hex) { int numChars = hex.Length; byte[] bytes = new byte[numChars / 2]; for (int i = 0; i < numChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; }
Performance Optimization
For optimal performance, especially with large datasets, avoid using Convert.ToByte
with Substring
. Direct iteration and bit manipulation provide substantial performance improvements.
The above is the detailed content of How to Efficiently Convert Byte Arrays and Hex Strings in .NET?. For more information, please follow other related articles on the PHP Chinese website!