Converting C# byte[] Arrays to Hex Strings
Directly converting a byte[]
array to a string in C# often yields undesirable results, typically displaying "System.Byte[]". This guide shows how to efficiently convert a byte array to its hexadecimal (hex) string representation, addressing common issues.
Method 1: Using BitConverter
The BitConverter
class offers a simple solution:
<code class="language-csharp">byte[] data = { 1, 2, 4, 8, 16, 32 }; string hex = BitConverter.ToString(data); // Result: 01-02-04-08-10-20 string hexNoDashes = BitConverter.ToString(data).Replace("-", ""); // Result: 010204081020</code>
This method produces a hex string with or without hyphens separating the byte values.
Method 2: Using Base64 Encoding (Compact Representation)
For a more compact hexadecimal representation, consider Base64 encoding:
<code class="language-csharp">string base64 = Convert.ToBase64String(data); // Result (will vary): AQIECBAg</code>
Base64 encoding provides a shorter string representation, although it's not strictly a hexadecimal format. Choose this method if space efficiency is paramount. Note that the resulting string will not be directly interpretable as hexadecimal.
The above is the detailed content of How to Convert a byte[] Array to a Hex String in C#?. For more information, please follow other related articles on the PHP Chinese website!