Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Strings and Text

Convert.ToHexString() and FromHexString()

Reference for hexadecimal text in C#: Convert.ToHexString, FromHexString, ToHexStringLower, the buffer overload, and formatting numbers as hex.

Hexadecimal writes each byte as two characters (00 to FF). It is the usual way to show hashes, GUID parts, binary protocol dumps and color values. Convert.ToHexString turns a byte array into an uppercase hex string, and Convert.FromHexString parses it back. Since .NET 9 there is also Convert.ToHexStringLower for lowercase output.

For a single number, use the X format specifier instead: 255.ToString("X2") gives FF. Byte-sequence helpers are shorter than the old BitConverter.ToString(bytes).Replace("-", "") trick, and faster.

C#
string hex = Convert.ToHexString(new byte[] { 222, 173, 190, 239 });   // "DEADBEEF"
byte[] bytes = Convert.FromHexString(hex);

Try it

C# Bytes to hex and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Numbers, formatting and bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public static string Convert.ToHexString(byte[] inArray);
public static string Convert.ToHexString(byte[] inArray, int offset, int length);
public static string Convert.ToHexString(ReadOnlySpan<byte> bytes);
public static string Convert.ToHexStringLower(ReadOnlySpan<byte> bytes);          // .NET 9
public static byte[] Convert.FromHexString(string s);
public static byte[] Convert.FromHexString(ReadOnlySpan<char> chars);
public static OperationStatus Convert.FromHexString(ReadOnlySpan<char> source, Span<byte> destination,
                                                    out int charsConsumed, out int bytesWritten);   // .NET 9
Name Description
inArray / bytes / source The bytes to convert to text.
offset, length Optional slice of the array.
s / chars Hex text to parse, two characters per byte, upper or lower case.
destination Buffer you provide for the span overload, with charsConsumed and bytesWritten as out values.

Returns: a string (two characters per byte), a byte[], or, for the buffer overload, an OperationStatus (Done, DestinationTooSmall, NeedMoreData, InvalidData) plus the counts consumed and written.

Errors / undefined behavior: FromHexString throws FormatException for an odd number of characters or any character that is not 0-9, a-f or A-F (spaces, 0x prefixes and dashes included). ArgumentNullException for null. The buffer overload does not throw for bad data: it returns InvalidData, NeedMoreData (odd length, as the example shows) or DestinationTooSmall.

Usage notes

  • Uppercase by default. ToHexString writes A-F. Use ToHexStringLower (or .ToLowerInvariant() on older runtimes) when a protocol expects lowercase, such as many hash displays.
  • No separators. The text has no spaces, dashes or prefix. For a spaced dump use Convert.ToHexString(bytes) and insert separators yourself, or BitConverter.ToString(bytes) (which writes DE-AD-BE-EF).
  • Always two digits per byte. 0x05 becomes 05, never 5, so the text length is exactly 2 * bytes.Length.
  • Single numbers use format strings. ToString("X2") formats one byte, ToString("X") has no padding, and ToString("x8") pads to eight lowercase digits. Parse numbers with NumberStyles.HexNumber or Convert.ToInt32(text, 16). Neither accepts a 0x prefix with HexNumber; strip it first.
  • Byte order matters. Hex of an int formatted with X shows the most significant digit first, while BitConverter.GetBytes returns bytes in the machine's order (little-endian on x86 and ARM). Use BinaryPrimitives for a defined order.
  • Comparing hashes. To compare secret hashes or tokens, decode both sides and use CryptographicOperations.FixedTimeEquals, not string equality, which can leak timing information.
  • Performance. The methods are vectorized and allocate one string. The buffer overload allocates nothing.