Home >Backend Development >C++ >How Can I Convert a Byte Array to a Hexadecimal String in C#?
C# Byte Array to Hex String Conversion Techniques
This article explores efficient methods for converting a byte array into its hexadecimal string equivalent in C#.
Method 1: Leveraging BitConverter
The BitConverter
class offers a straightforward approach. The following example showcases its usage:
<code class="language-csharp">byte[] byteArray = { 1, 2, 4, 8, 16, 32 }; string hexString = BitConverter.ToString(byteArray); Console.WriteLine(hexString); // Output: 01-02-04-08-10-20</code>
Notice the hyphens separating the hexadecimal values. To eliminate these, use Replace()
:
<code class="language-csharp">hexString = BitConverter.ToString(byteArray).Replace("-", ""); Console.WriteLine(hexString); // Output: 010204081020</code>
Method 2: Utilizing Base64 Encoding
An alternative is to employ Base64 encoding. Base64 translates binary data into an ASCII string. This method often yields a more compact result:
<code class="language-csharp">string base64String = Convert.ToBase64String(byteArray); Console.WriteLine(base64String); // Output: AQIECBAg</code>
Choose the method that best suits your needs; Base64 is generally more space-efficient, while BitConverter
provides a direct hexadecimal representation.
The above is the detailed content of How Can I Convert a Byte Array to a Hexadecimal String in C#?. For more information, please follow other related articles on the PHP Chinese website!