Turning Bytes into Strings and Back: The Magic of Hexadecimal Code in C#
\n\nHave you ever wondered how a computer sees an image, music, or just a text file? It's all just a sequence of bytes. But bytes are not very convenient to display to a user or transmit in a URL. That's where the hexadecimal string (hex string) comes to the rescue — a compact and readable representation of binary data.
\n\nImagine: you're writing a cryptographic module, working with hashes, transmitting binary data via JSON, or logging packet contents. And then — bam! — you need to turn a byte array into a readable string. Or vice versa, restore the original bytes from a hex string. Sounds familiar? This question is one of the most popular on Stack Overflow, and today we'll settle it once and for all. Welcome to pythonlib.ru — your guide in the world of programming.
\n\nWhy Convert a Byte Array to a Hex String at All?
\n\nLet's get straight to the point. A byte array (byte[]) is raw data: numbers from 0 to 255. They are difficult for humans to read, and in some text protocols (HTTP, JSON) they can even break the format. A hex string solves both problems:
\n\n- \n
- Compactness: one byte turns into two characters (e.g., 255 → "FF"). \n
- Safety: the string contains only safe characters (0-9, A-F). \n
- Convenience: hex strings are easy to copy, compare, and log. \n
You've probably seen such strings in MD5, SHA256 hashes, or authorization tokens. Now you know how it works "under the hood."
\n\nMethod #1: The Classic — BitConverter (Simple and Fast)
\n\nThe most popular way in C# is to use the built-in BitConverter class. It has been in .NET since the very first version and works without any extra fuss.
Converting byte[] → hex string
\n\nbyte[] data = { 0x0F, 0x1A, 0xFF, 0x00 };\nstring hexString = BitConverter.ToString(data);\nConsole.WriteLine(hexString); // Output: 0F-1A-FF-00\n\nSimple, right? But there's a nuance: a hyphen is inserted between character pairs. If the hyphen bothers you, it's easy to remove:
\n\nstring hexString = BitConverter.ToString(data).Replace("-", "");\nConsole.WriteLine(hexString); // Output: 0F1AFF00\n\nPros: minimal code, built-in method, understandable for beginners.
\nCons: extra hyphen (needs removal), slight memory allocation for intermediate strings.
Reverse Conversion: hex string → byte[]
\n\nThe reverse operation is a bit more complex. BitConverter only works one way. But we don't give up — let's write a simple parser:
\n\npublic static byte[] HexStringToBytes(string hex)\n{\n // Remove possible hyphens and spaces\n hex = hex.Replace("-", "").Replace(" ", "");\n int length = hex.Length;\n byte[] bytes = new byte[length / 2];\n for (int i = 0; i < length; i += 2)\n {\n bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);\n }\n return bytes;\n}\n\n// Usage:\nstring hex = "0F1AFF00";\nbyte[] result = HexStringToBytes(hex);\n// result: { 0x0F, 0x1A, 0xFF, 0x00 }\n\nThis method uses Convert.ToByte with base 16 — reliable and readable. However, for large arrays, Substring creates many temporary strings. For production code, it's better to use Span<T> or a loop with character indexing.
Method #2: Modern — Convert.ToHexString (.NET 5+)
\n\nStarting with .NET 5, Microsoft added the long-awaited Convert.ToHexString method. It works fast and without hyphens.
byte[] data = { 0x0F, 0x1A, 0xFF, 0x00 };\nstring hexString = Convert.ToHexString(data);\nConsole.WriteLine(hexString); // Output: 0F1AFF00\n\nBeautiful! No hyphens, no Replace. And for the reverse operation, there is Co