Convert byte array to hex string in .NET
When working with binary data, converting it to a hexadecimal representation can improve readability and analysis efficiency. However, displaying the byte array directly as a string results in "System.Byte[]" being output instead of the expected value.
.NET provides a built-in method BitConverter.ToString() to solve this problem, which can convert a byte array into a hexadecimal string.
convert to hexadecimal
To convert a byte array to a hex string, just use the following code:
<code class="language-csharp">byte[] data = { 1, 2, 4, 8, 16, 32 }; string hex = BitConverter.ToString(data);</code>
This will generate a string with dashes between hexadecimal values, such as "01-02-04-08-10-20".
Remove dashes
If you want a string without dashes, you can remove them using the Replace() method:
<code class="language-csharp">string hex = BitConverter.ToString(data).Replace("-", string.Empty);</code>
This will generate a string like "010204081020".
Alternate representation: Base64
For a more compact representation, you can use the Convert.ToBase64String() method:
<code class="language-csharp">string base64 = Convert.ToBase64String(data);</code>
This will encode the data using Base64 encoding, resulting in a printable ASCII string.
The above is the detailed content of How to Convert a Byte Array to a Hexadecimal String in .NET?. For more information, please follow other related articles on the PHP Chinese website!