Home > Backend Development > C++ > How to Convert a byte[] Array to a Hex String in C#?

How to Convert a byte[] Array to a Hex String in C#?

DDD
Release: 2025-01-20 11:21:09
Original
444 people have browsed it

How to Convert a byte[] Array to a Hex String in C#?

Converting C# byte[] Arrays to Hex Strings

Directly converting a byte[] array to a string in C# often yields undesirable results, typically displaying "System.Byte[]". This guide shows how to efficiently convert a byte array to its hexadecimal (hex) string representation, addressing common issues.

Method 1: Using BitConverter

The BitConverter class offers a simple solution:

<code class="language-csharp">byte[] data = { 1, 2, 4, 8, 16, 32 };
string hex = BitConverter.ToString(data); // Result: 01-02-04-08-10-20
string hexNoDashes = BitConverter.ToString(data).Replace("-", ""); // Result: 010204081020</code>
Copy after login

This method produces a hex string with or without hyphens separating the byte values.

Method 2: Using Base64 Encoding (Compact Representation)

For a more compact hexadecimal representation, consider Base64 encoding:

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

Base64 encoding provides a shorter string representation, although it's not strictly a hexadecimal format. Choose this method if space efficiency is paramount. Note that the resulting string will not be directly interpretable as hexadecimal.

The above is the detailed content of How to Convert a byte[] Array to a Hex 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template