Hex in .NET
- Text to hex:
Convert.ToHexString(Encoding.UTF8.GetBytes(text)). It writes uppercase with no separators;Convert.ToHexStringLower(.NET 9 and later) writes lowercase;BitConverter.ToString(bytes)writes "48-65-6C", the style older code and logs use. - Hex to text:
Encoding.UTF8.GetString(Convert.FromHexString(hex)).FromHexStringaccepts either case but no spaces, dashes or0x: remove those first. An odd number of digits throws a FormatException. - The encoding decides the bytes. "é" is
C3 A9in UTF-8,E9 00in UTF-16 (Encoding.Unicode) andE9in Latin-1;Encoding.ASCIIwrites3F, a question mark, for anything it cannot represent.
Hex that does not decode cleanly in the chosen encoding shows U+FFFD (�), as GetString does: the bytes are not text in that encoding, or are text in another one.
FAQ
How do I convert a string to hex in C#?
Convert.ToHexString(Encoding.UTF8.GetBytes(text)), or Convert.ToHexStringLower on .NET 9 and later for lowercase.
How do I convert hex to a string in C#?
Encoding.UTF8.GetString(Convert.FromHexString(hex)). Remove spaces, dashes and 0x prefixes first; FromHexString accepts only the digits.
Why do I get different hex for the same text?
Different encodings. UTF-8 and UTF-16 give different bytes for everything outside ASCII, and UTF-16 gives two bytes even for ASCII letters.