Home >Backend Development >C++ >How to Convert Between Byte Arrays and Hexadecimal Strings in C#?

How to Convert Between Byte Arrays and Hexadecimal Strings in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-02-03 08:13:09884browse

How to Convert Between Byte Arrays and Hexadecimal Strings in C#?

C# medium -byte array array and hexadecimal strings are transformed.

In programming, the conversion between byte array and hexadecimal string is a common task. This article will introduce how to achieve this conversion in C#:

Converted from byte array to hexadecimal string

From the .NET 5, you can use the built -in method to complete this task:

Convert.ToHexString The converted from the hexadecimal string to the byte array

<code class="language-csharp">string hexString = Convert.ToHexString(byteArray);</code>

For reverse operation, please use :

The alternative method of the old version .NET version Convert.FromHexString

<code class="language-csharp">byte[] byteArray = Convert.FromHexString(hexString);</code>
If you are using the old version .NET, you can use the following methods:

or:

reverse conversion

<code class="language-csharp">public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}</code>

To convert the hexadecimal string conversion tote array, please use this method:

<code class="language-csharp">public static string ByteArrayToString(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-", "");
}</code>

Optimize

In order to improve performance, you can consider using alternatives to avoid string -based conversion. However, for most scenarios, the method introduced here should be sufficient.

The above is the detailed content of How to Convert Between Byte Arrays and Hexadecimal Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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