[C#]Converting and Formatting Byte Arrays to Hexadecimal Strings

目次

Overview

This implementation converts binary data (byte[]) into readable hexadecimal strings, which is useful for debugging logs or displaying hash values (MD5/SHA256). It covers both direct conversion using standard .NET methods and formatted output (using spaces or line breaks) for better readability.

Specifications (Input/Output)

  • Input: Any byte array (byte[]).
  • Output: A hexadecimal string (e.g., 4A30...). Includes delimiters like spaces or hyphens and line breaks if needed.
  • Prerequisite: The Convert.ToHexString method is available in .NET 5 and later. For older versions like .NET Framework, use BitConverter.

Basic Usage

The simplest way to convert a byte array into a continuous hex string without delimiters:

byte[] data = { 0xAB, 0xCD, 0xEF };

// .NET 5 or later (Recommended)
string hex = Convert.ToHexString(data); 
// Result: "ABCDEF"

// .NET Framework / Older environments
string hexOld = BitConverter.ToString(data).Replace("-", "");
// BitConverter returns "AB-CD-EF", so you must remove the hyphens.

Full Code

This console application implements two patterns: one for getting a clean string and another for formatted console output.

using System;
using System.Text;
using System.Linq;

class Program
{
    static void Main()
    {
        // 1. Dummy data for testing (32 bytes)
        // Generates sequential data from 00 to 1F
        byte[] buffer = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray();

        Console.WriteLine("--- 1. Bulk Conversion to String ---");
        
        // .NET 5 or later: Fastest and most concise
        string hexSimple = Convert.ToHexString(buffer);
        Console.WriteLine($"[Simple]: {hexSimple}");

        // BitConverter: Useful if you need hyphen delimiters
        string hexHyphen = BitConverter.ToString(buffer);
        Console.WriteLine($"[Hyphen]: {hexHyphen}");

        Console.WriteLine();
        Console.WriteLine("--- 2. Formatted Output via Loop ---");

        // Process each byte to display with spaces
        // Using StringBuilder offers better performance
        StringBuilder sb = new StringBuilder();
        
        foreach (byte b in buffer)
        {
            // "X2" = Uppercase 2-digit hex, "x2" = Lowercase
            sb.Append($"{b:X2} ");
        }
        
        Console.WriteLine($"[Formatted]: {sb.ToString().TrimEnd()}");
    }
}

Execution Result Example

--- 1. Bulk Conversion to String ---
[Simple]: 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
[Hyphen]: 00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F-10-11-12-13-14-15-16-17-18-19-1A-1B-1C-1D-1E-1F

--- 2. Formatted Output via Loop ---
[Formatted]: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F

Customization Points

  • Uppercase and Lowercase: The format specifier X2 outputs uppercase (A–F), while x2 outputs lowercase (a–f).
  • Changing Delimiters: BitConverter.ToString uses hyphens by default. You can use .Replace("-", ":") to create MAC address styles.
  • Using StringBuilder: Calling Console.Write repeatedly in a loop is slow. When handling large data, collect it in a StringBuilder before outputting.

Points of Caution

  • Memory Usage: A hexadecimal string uses two characters (2 bytes in C# strings) for every single byte of data. Converting a huge binary file to a string will consume more than twice the memory of the original data.
  • BitConverter Behavior: BitConverter.ToString() always inserts hyphens between elements. While removing them with .Replace("-", "") is common, it creates unnecessary intermediate strings. For better performance, use Convert.ToHexString (.NET 5+).

Application

Binary Editor Style Hex Dump

This is a more advanced example that adds line breaks every 16 bytes and displays the offset position.

public static void PrintHexDump(byte[] data)
{
    for (int i = 0; i < data.Length; i++)
    {
        // Display offset at the start of each line (e.g., 0000: )
        if (i % 16 == 0)
        {
            Console.Write($"{i:X4}: ");
        }

        // Hex display of the data
        Console.Write($"{data[i]:X2} ");

        // Line break every 16 bytes
        if ((i + 1) % 16 == 0)
        {
            Console.WriteLine();
        }
    }
    // Final line break
    Console.WriteLine();
}

Summary

For simple conversions in modern .NET environments, Convert.ToHexString is the most efficient and concise option. If you need to format data for debugging or support older frameworks, use a combination of BitConverter or StringBuilder with loop processing.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次