Home > Backend Development > C++ > How Can I Convert a Byte Array to a Hexadecimal String in C#?

How Can I Convert a Byte Array to a Hexadecimal String in C#?

Patricia Arquette
Release: 2025-01-20 11:26:13
Original
989 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template