Frequently, developers need to convert byte arrays into strings. However, directly converting often yields decimal values, not the desired hexadecimal format. This guide shows how to achieve proper hexadecimal (and Base64) string representations.
The simplest method uses the built-in BitConverter.ToString()
function. This returns a hexadecimal string with hyphens separating each byte value:
<code class="language-csharp">byte[] data = { 1, 2, 4, 8, 16, 32 }; string hex = BitConverter.ToString(data); </code>
This produces:
<code>Result: 01-02-04-08-10-20</code>
To remove the hyphens, use string manipulation:
<code class="language-csharp">string hex = BitConverter.ToString(data).Replace("-", string.Empty);</code>
This yields:
<code>Result: 010204081020</code>
For a more compact representation, consider Base64 encoding:
<code class="language-csharp">string base64 = Convert.ToBase64String(data);</code>
The output will be:
<code>Result: AQIECBAg</code>
These methods provide efficient conversion of byte arrays to strings in either hexadecimal or Base64 formats, meeting various development needs.
The above is the detailed content of How Can I Convert Byte Arrays to Hexadecimal Strings in .NET?. For more information, please follow other related articles on the PHP Chinese website!