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
Release: 2025-02-03 08:13:09
Original
807 people have browsed it

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

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

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

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!

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