Avatar ·

How to convert a byte array to a hexadecimal string and back in C#?

Hello everyone! I'm a beginner C# developer, and I encountered a problem when working with binary data. I need to save a byte array (e.g., a SHA256 hash) to a text file and then read it back. I realized that simply writing the bytes as-is doesn't work — it produces garbled text. I need to convert them into a string of hexadecimal characters, and then when reading, convert that string back into a byte array.

\n\n

I tried to do it myself, but my code doesn't work correctly. Here's what I wrote:

\n\n
byte[] data = { 0x0F, 0xBA, 0x01, 0xFF };\nstring hex = "";\nforeach (byte b in data)\n{\n    hex += b.ToString("X");\n}\n// Result is "FBA1FF" — without leading zeros!\nConsole.WriteLine(hex);
\n\n

When I try to read this string back, I can't figure out where the