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
string hexString = Convert.ToHexString(byteArray);
For reverse operation, please use :
<旧> The alternative method of the old version .NET version Convert.FromHexString
byte[] byteArray = Convert.FromHexString(hexString);
or: <或者>
<向> reverse conversion
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(); }
To convert the hexadecimal string conversion tote array, please use this method:
public static string ByteArrayToString(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); }
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!