Home >Backend Development >C++ >How to Efficiently Convert Byte Arrays to Hexadecimal Strings and Vice Versa?
Efficiently Converting Byte Arrays and Hexadecimal Strings
Many applications require converting byte arrays to hexadecimal strings and vice versa. This article explores efficient methods for this conversion in .NET.
Byte Array to Hexadecimal String
.NET 5 and later offer the simplest solution using Convert.ToHexString
:
<code class="language-csharp">byte[] byteArray = { 1, 2, 3 }; string hexString = Convert.ToHexString(byteArray); </code>
For older .NET frameworks, two alternatives provide similar functionality:
Method 1 (Using StringBuilder):
<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>
Method 2 (Using BitConverter):
<code class="language-csharp">public static string ByteArrayToHex(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); }</code>
Hexadecimal String to Byte Array
Converting a hexadecimal string back to a byte array can be achieved with this method:
<code class="language-csharp">public static byte[] HexToByteArray(string hex) { int len = hex.Length; byte[] arr = new byte[len / 2]; for (int i = 0; i < len; i += 2) { arr[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); } return arr; }</code>
For enhanced performance, utilizing Substring
with Convert.ToByte
directly avoids unnecessary intermediate conversions. This approach is particularly beneficial when dealing with large byte arrays.
The above is the detailed content of How to Efficiently Convert Byte Arrays to Hexadecimal Strings and Vice Versa?. For more information, please follow other related articles on the PHP Chinese website!