Home > Backend Development > C++ > How to Convert a Byte Array to a Hexadecimal String in .NET?

How to Convert a Byte Array to a Hexadecimal String in .NET?

Patricia Arquette
Release: 2025-01-20 11:12:13
Original
1000 people have browsed it

How to Convert a Byte Array to a Hexadecimal String in .NET?

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

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

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

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!

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