How do you convert a byte array to a hexadecimal string in C#, and vice versa?

To convert a byte array to a hexadecimal string and vice versa in C#, use the following methods:

1. Byte Array to Hexadecimal String

public static string ToHexString(byte[] bytes, bool uppercase = true)
{
    StringBuilder hex = new StringBuilder(bytes.Length * 2);
    string format = uppercase ? "X2" : "x2";
    foreach (byte b in bytes)
        hex.Append(b.ToString(format));
    return hex.ToString();
}

Example Usage:

byte[] data = { 0xAB, 0xCD, 0x1F };
string hexString = ToHexString(data); // "ABCD1F" (uppercase)
string hexLower = ToHexString(data, false); // "abcd1f" (lowercase)

2. Hexadecimal String to Byte Array

public static byte[] FromHexString(string hex)
{
    if (hex.Length % 2 != 0)
        throw new ArgumentException("Hex string must have even length.");

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

Example Usage:

string hex = "ABCD1F";
byte[] bytes = FromHexString(hex); // Returns { 0xAB, 0xCD, 0x1F }

Key Notes

  1. Case Insensitivity:
    FromHexString works with both uppercase (e.g., "AB") and lowercase (e.g., "ab") hex characters.
  2. Validation:
  • FromHexString throws an ArgumentException if the hex string has an odd length.
  • Invalid characters (e.g., "GH") throw a FormatException.
  1. Performance:
  • StringBuilder avoids string concatenation overhead for large byte arrays.
  • For critical performance scenarios, consider using Span<T> or lookup tables.

Alternative Using LINQ (Byte Array to Hex)

For concise code (less performant for large arrays):

public static string ToHexStringLinq(byte[] bytes, bool uppercase = true)
{
    return string.Join("", bytes.Select(b => b.ToString(uppercase ? "X2" : "x2")));
}

Alternative Using BitConverter (Hex to Byte Array)

For .NET 5+ with System.Convert optimizations:

public static byte[] FromHexStringFast(string hex)
{
    ReadOnlySpan<char> hexSpan = hex.AsSpan();
    byte[] bytes = new byte[hexSpan.Length / 2];
    for (int i = 0; i < bytes.Length; i++)
    {
        bytes[i] = Convert.ToByte(hexSpan.Slice(i * 2, 2).ToString(), 16);
    }
    return bytes;
}

Handling Invalid Characters

Add validation to check for non-hex characters:

public static bool IsValidHexString(string hex)
{
    return hex.All(c => (c >= '0' && c <= '9') || 
                        (c >= 'A' && c <= 'F') || 
                        (c >= 'a' && c <= 'f'));
}

Summary

  • To Hex: Use ToString("X2") for uppercase or ToString("x2") for lowercase.
  • From Hex: Split the string into 2-character chunks and parse with Convert.ToByte.
  • Always validate hex strings for even length and valid characters before conversion.

Leave a Reply

Your email address will not be published. Required fields are marked *