In C#, Convert.TryToHexString writes hex digits into a destination Span<char>.
Returns false when the destination cannot hold two characters per byte. Available on newer .NET versions.
This is a static member of System.Convert. You call it with the type name, such as Convert.TryToHexString(...). Convert is the everyday API for converting between common CLR types in C#.
Syntax
Pass source bytes and a destination char span.
C#
byte[] data = { 0x0A, 0x1B };
Span<char> dest = stackalloc char[4];
bool ok = Convert.TryToHexString(data, dest, out int written);
Call
What it does
Convert.TryToHexString(data, dest, out written)
true if dest is large enough.
Need 2 * byteCount characters of space. On failure, written is 0.
Library declarations
C#
public static bool TryToHexString(ReadOnlySpan<byte> source,
Span<char> destination, out int charsWritten);
Parameters
Parameter
Description
source
Required. Bytes to encode.
destination
Required. Char buffer for hex digits.
charsWritten
Out. Characters written on success.
Return Value
Return Value
Description
true
Hex text written.
false
Destination too small.
C# Examples
Example 1 — Fit Hex into Four Chars
Encode two bytes into a 4-char span.
C#
using System;
class Program {
static void Main() {
byte[] data = { 0x0A, 0x1B };
Span<char> dest = stackalloc char[4];
bool ok = Convert.TryToHexString(data, dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(new string(dest.Slice(0, written)));
}
}
Output
True
0A1B
How It Works
4 chars needed. Two bytes × two digits.
ok true. Buffer size matched.
0A1B. Same text as ToHexString.
stackalloc. No heap string until you build one.
Example 2 — False for Tiny Buffer
Attempt encode into a 2-char span.
C#
using System;
class Program {
static void Main() {
byte[] data = { 0x0A, 0x1B };
Span<char> dest = stackalloc char[2];
bool ok = Convert.TryToHexString(data, dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(written);
}
}
Output
False
0
How It Works
Only 2 slots. Need 4 for two bytes.
false. Try refuses without throwing.
written 0. Output not usable.
Grow and retry. Allocate a larger span.
Example 3 — Show Character Count
Print how many hex chars were produced.
C#
using System;
class Program {
static void Main() {
byte[] data = { 255 };
char[] buf = new char[8];
bool ok = Convert.TryToHexString(data, buf, out int written);
Console.WriteLine(ok + " " + written);
Console.WriteLine(new string(buf, 0, written));
}
}
Output
True 2
FF
How It Works
One byte. Needs exactly two hex digits.
True 2. Success and count.
FF. Uppercase hex for 255.
char[] works. Arrays become spans automatically.
Frequently Asked Questions
At least 2 × number of bytes.
Span Try helpers are modern .NET APIs.
ToHexString returns a new string in one call.
Usually the destination was too small.
ToHexString is uppercase; change case afterward if needed.