Efficient Conversion Between Byte Arrays and Hexadecimal Strings in C#

Oct 27, 2025 · Programming · 28 views · 7.8

Keywords: C# | Byte Array | Hexadecimal | Conversion | Performance

Abstract: This article comprehensively explores methods for converting byte arrays to hexadecimal strings and vice versa in C#, covering modern approaches in .NET 5 and later, such as Convert.ToHexString and Convert.FromHexString, as well as legacy methods using StringBuilder and BitConverter for older versions. It includes performance analysis, highlighting optimization techniques like lookup tables, and provides rewritten code examples with step-by-step explanations to aid developers in selecting the best approach for their projects.

Introduction

Converting between byte arrays and hexadecimal strings is a common requirement in programming, particularly in fields like cryptography, data serialization, and network communication. Byte arrays represent binary data, while hexadecimal strings offer a human-readable format. C# provides various methods for this conversion, ranging from simple built-in functions to high-performance custom implementations. Based on high-scoring answers from Stack Overflow and supplementary references, this article systematically reviews these methods, delving into their performance and practical applications.

Modern Conversion Methods in .NET 5 and Later

Starting with .NET 5, the framework includes efficient built-in functions for conversion. The Convert.ToHexString method converts a byte array to a hexadecimal string, and Convert.FromHexString handles the reverse operation. These methods are optimized and recommended for new projects to ensure code simplicity and performance.

// Example using Convert.ToHexString
byte[] byteArray = { 0x12, 0x34, 0x56 };
string hexString = Convert.ToHexString(byteArray);
// hexString results in "123456"

// Reverse conversion example
byte[] restoredArray = Convert.FromHexString(hexString);

These functions require no additional processing and are suitable for most scenarios, avoiding the overhead of manual loops.

Legacy Conversion Methods for Older .NET Versions

For older .NET frameworks, developers must rely on custom methods. Common approaches include using StringBuilder and BitConverter. The StringBuilder method iterates through the byte array, formatting each byte as a two-digit hexadecimal number; the BitConverter method leverages built-in conversion but requires removing delimiters.

// Method using StringBuilder
public static string ConvertByteArrayToHexString(byte[] bytes)
{
    var hexBuilder = new StringBuilder(bytes.Length * 2);
    foreach (var b in bytes)
    {
        hexBuilder.AppendFormat("{0:x2}", b);
    }
    return hexBuilder.ToString();
}

// Method using BitConverter
public static string ConvertByteArrayToHexStringViaBitConverter(byte[] bytes)
{
    string hex = BitConverter.ToString(bytes);
    return hex.Replace("-", "");
}

The StringBuilder method balances readability and performance, while the BitConverter approach offers concise code but may be slightly slower due to string replacement operations.

Reverse Conversion: From Hexadecimal String to Byte Array

Reverse conversion involves parsing a hexadecimal string into bytes. A common method uses a loop with Convert.ToByte, processing characters in pairs.

public static byte[] ConvertHexStringToByteArray(string hex)
{
    int charCount = hex.Length;
    byte[] bytes = new byte[charCount / 2];
    for (int i = 0; i < charCount; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    }
    return bytes;
}

This approach is straightforward and reliable, but performance may be impacted by Substring and Convert.ToByte. For high-performance needs, consider avoiding these calls and using byte manipulation instead.

Performance Analysis and Optimization

Performance tests indicate that lookup-based methods are generally the fastest, though they increase code complexity. For instance, using precomputed lookup arrays can significantly speed up conversions, especially with large datasets. Unsafe code versions, such as pointer operations, can further optimize performance but sacrifice readability and safety.

// Example: Fast conversion using a lookup table
static string[] hexTable = {
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
    // ... full table from 0x00 to 0xFF
};

public static string ConvertByteArrayToHexStringViaLookup(byte[] bytes)
{
    var result = new StringBuilder(bytes.Length * 2);
    foreach (byte b in bytes)
    {
        result.Append(hexTable[b]);
    }
    return result.ToString();
}

In practice, the choice of method should depend on data size and performance requirements. Built-in methods suffice for small-scale data, while lookup tables or byte manipulation may be better for large-scale processing.

Detailed Code Examples

Below are rewritten code examples that emphasize core logic. The StringBuilder method builds the result by iterating through the byte array with formatted strings; the BitConverter method relies on framework capabilities but requires post-processing. For reverse conversion, a loop ensures accurate parsing of the string.

// Comprehensive example: Byte array to hexadecimal string
public static string ByteArrayToHex(byte[] data)
{
    return BitConverter.ToString(data).Replace("-", "");
}

// Comprehensive example: Hexadecimal string to byte array
public static byte[] HexToByteArray(string hex)
{
    int len = hex.Length;
    byte[] result = new byte[len / 2];
    for (int i = 0; i < len; i += 2)
    {
        result[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    }
    return result;
}

These examples demonstrate basic implementations; developers can add error handling, such as verifying that the string length is even.

Conclusion

Converting between byte arrays and hexadecimal strings in C# can be achieved through various methods. Modern .NET versions favor built-in functions for simplicity; older versions rely on StringBuilder and BitConverter as dependable options. For performance optimization, lookup-based methods excel but require complexity trade-offs. In real-world development, the best approach should be selected based on project needs, .NET version, and performance testing. The code and analysis provided in this article aim to help developers efficiently address these conversions, enhancing application reliability and efficiency.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.