Home > Backend Development > C++ > How Can I Convert Byte Arrays to Hexadecimal Strings in .NET?

How Can I Convert Byte Arrays to Hexadecimal Strings in .NET?

DDD
Release: 2025-01-20 11:31:10
Original
285 people have browsed it

How Can I Convert Byte Arrays to Hexadecimal Strings in .NET?

.NET Byte Array to Hexadecimal String Conversion

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>
Copy after login

This produces:

<code>Result: 01-02-04-08-10-20</code>
Copy after login

To remove the hyphens, use string manipulation:

<code class="language-csharp">string hex = BitConverter.ToString(data).Replace("-", string.Empty);</code>
Copy after login

This yields:

<code>Result: 010204081020</code>
Copy after login

For a more compact representation, consider Base64 encoding:

<code class="language-csharp">string base64 = Convert.ToBase64String(data);</code>
Copy after login

The output will be:

<code>Result: AQIECBAg</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template