Home >Backend Development >C++ >How to Efficiently Convert Byte Arrays and Hex Strings in .NET?

How to Efficiently Convert Byte Arrays and Hex Strings in .NET?

Patricia Arquette
Patricia ArquetteOriginal
2025-02-03 08:23:09360browse

How to Efficiently Convert Byte Arrays and Hex Strings in .NET?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn