In C#, Convert.ToHexString turns each byte into two hex digits (0–9, A–F).
It ships with .NET 5 and later. For older frameworks, format bytes manually or use BitConverter style helpers.
This is a static member of System.Convert. You call it with the type name, such as Convert.ToHexString(...). Convert is the everyday API for converting between common CLR types in C#.
Output uses uppercase hex digits. Pair with FromHexString to decode.
Library declarations
C#
public static string ToHexString(byte[] bytes);
public static string ToHexString(ReadOnlySpan<byte> bytes);
Parameters
Parameter
Description
bytes
Required. Bytes to encode as hex.
Return Value
Return Value
Description
string
Hex text with two digits per byte.
C# Examples
Example 1 — Bytes to Hex Text
Encode two bytes and print the hex string.
C#
using System;
class Program {
static void Main() {
byte[] data = { 0x0A, 0x1B };
Console.WriteLine(Convert.ToHexString(data));
}
}
Output
0A1B
How It Works
Two bytes. 0x0A and 0x1B keep the sample tiny.
ToHexString. Emits two digits per byte.
0A1B. Uppercase hex characters.
No separators. Digits are contiguous.
Example 2 — Hex of "Hi"
Encode UTF-8 bytes of a short word.
C#
using System;
using System.Text;
class Program {
static void Main() {
byte[] data = Encoding.UTF8.GetBytes("Hi");
Console.WriteLine(Convert.ToHexString(data));
}
}
Output
4869
How It Works
UTF-8. "H" is 0x48, "i" is 0x69.
Hex text. Becomes 4869.
Readable dump. Handy for debugging payloads.
Round-trip. FromHexString can restore the bytes.
Example 3 — Empty Array Edge
Show encoding an empty byte array.
C#
using System;
class Program {
static void Main() {
byte[] data = Array.Empty<byte>();
string hex = Convert.ToHexString(data);
Console.WriteLine(hex.Length);
Console.WriteLine(hex == "");
}
}
Output
0
True
How It Works
No bytes. Empty input is valid.
Length 0. Result string is empty.
Equals "". Confirms empty text.
Safe default. Useful when optional payloads are missing.
Frequently Asked Questions
ToHexString requires .NET 5 or newer.
ToHexString uses uppercase A–F.
No—anyone can decode it.
Convert.FromHexString or TryFromHexString.
The API returns contiguous digits; add dashes yourself if needed.