How do you convert a byte array to a hexadecimal string, and vice versa in C#?
Below are two common approaches for converting byte arrays to hexadecimal strings and vice versa. One uses built-in .NET functionality with a bit of string manipulation, and the other relies on manual parsing.
Converting a Byte Array to a Hex String
One of the easiest ways to transform a byte array into a hex string is to use BitConverter.ToString()
, then remove the hyphens:
public static string ByteArrayToHexString(byte[] bytes) { // Produces something like "0A-1B-FF" string hexWithHyphens = BitConverter.ToString(bytes); // Remove hyphens => "0A1BFF" string hexWithoutHyphens = hexWithHyphens.Replace("-", ""); return hexWithoutHyphens; }
Alternative: Custom Loop
If you need tighter control over the formatting, you can create a loop and manually format each byte:
public static string ByteArrayToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) sb.AppendFormat("{0:X2}", b); // Formats each byte in 2-digit uppercase hex return sb.ToString(); }
Converting a Hex String to a Byte Array
Reversing the process involves:
- Ensuring your hex string has an even number of characters (each byte corresponds to two hex digits).
- Parsing each pair of hex characters into a byte.
public static byte[] HexStringToByteArray(string hex) { if (hex.Length % 2 != 0) throw new ArgumentException("Hex string must have an even number of digits."); byte[] bytes = new byte[hex.Length / 2]; for (int i = 0; i < bytes.Length; i++) { string byteValue = hex.Substring(i * 2, 2); bytes[i] = Convert.ToByte(byteValue, 16); } return bytes; }
Tips and Best Practices
- Validate Input: Always confirm the hex string has an even number of characters.
- Case Sensitivity:
Convert.ToByte()
handles both uppercase ("AF"
) and lowercase ("af"
). - Performance: For large arrays, consider using
StringBuilder
or streaming approaches. - Hyphens/Delimiters: If your hex string contains separators (e.g.,
"0A-1B-FF"
), remove them before conversion.
Strengthen Your Coding Foundations
If you’d like to further refine your skills in C# and learn pattern-based solutions to common problems, check out these courses on DesignGurus.io:
- Grokking the Coding Interview: Patterns for Coding Questions
- Grokking Data Structures & Algorithms for Coding Interviews
For free tutorials and discussions about system design and coding best practices, visit the DesignGurus.io YouTube channel. This knowledge can be particularly handy when dealing with low-level manipulations like string-to-byte conversions in real-world projects or interviews.