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:
<code class="language-csharp">string hexString = Convert.ToHexString(byteArray);</code>
For older .NET frameworks, consider these alternatives:
<code class="language-csharp">hexString = ByteArrayToHex(byteArray);</code>
where ByteArrayToHex
is defined as:
<code class="language-csharp">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(); }</code>
Another viable option, though potentially less efficient:
<code class="language-csharp">hexString = BitConverter.ToString(byteArray).Replace("-", "");</code>
Converting Hex Strings to Byte Arrays
The reverse conversion is equally important:
<code class="language-csharp">byte[] byteArray = HexToStringArray(hexString);</code>
The HexToStringArray
function can be implemented as:
<code class="language-csharp">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; }</code>
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!