C#: converting byte array to hexadecimal string

Introduction

In this short tutorial we will learn how to convert a byte array to a hexadecimal string in C#.

This tutorial was tested with .NET Core 3.1.

The code

We will start the code by stating the namespaces we will be using. In our specific case, we will use the System namespace, which will give us access to the BitConverter static class. We will need this class for the conversion of the array to the hexadecimal string.

using System;

Moving on to the main code, we will define a byte array variable with some arbitrary bytes.

byte[] byteArray = { 0, 1, 2, 3, 4, 5, 10, 20, 254, 255 };

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it.

string hexString = BitConverter.ToString(byteArray);

Now that we have our string, we can simply print it to the console. Note that the string consists on hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in the input array [1].

Console.WriteLine(hexString);

Naturally if we want a separator other than a hyphen, we can simply apply a string Replace to this string. To exemplify, we will replace the hyphens by empty spaces.

Console.WriteLine(hexString.Replace('-', ' '));

Our complete C# code can be seen below.

namespace BitConv
{
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            byte[] byteArray = { 0, 1, 2, 3, 4, 5, 10, 20, 254, 255 };
            string hexString = BitConverter.ToString(byteArray);

            Console.WriteLine(hexString);
            Console.WriteLine(hexString.Replace('-', ' '));

        }
    }
}

Testing the code

To test the code, simply compile it and run it in a tool of your choice. In my case, I’m using Visual Studio 2019.

You should get an output similar to figure 1. As can be seen, we have obtained two hexadecimal string representations of the byte array, as expected.

Output of the code, showing the hexadecimal strings representing the array.
Figure 1 – Output of the code, showing the hexadecimal strings representing the array.

References

[1] https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.tostring?view=netcore-3.1#System_BitConverter_ToString_System_Byte___

Leave a Reply

%d bloggers like this: