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>
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!