如何将字节数组转换为十六进制字符串,反之亦然? [英] How do you convert a byte array to a hexadecimal string, and vice versa?
问题描述
如何将字节数组转换为十六进制字符串,反之亦然?
How can you convert a byte array to a hexadecimal string, and vice versa?
推荐答案
您可以使用 Convert.ToHexString
从 .NET 5 开始.
还有一种反向操作的方法:Convert.FromHexString
.
You can use Convert.ToHexString
starting with .NET 5.
There's also a method for the reverse operation: Convert.FromHexString
.
对于旧版本的 .NET,您可以使用:
For older versions of .NET you can either use:
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();
}
或:
public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-","");
}
还有更多的变体,例如 这里.
There are even more variants of doing it, for example here.
反向转换如下:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
使用 Substring
是结合 Convert.ToByte
的最佳选择.有关详细信息,请参阅此答案.如果你需要更好的性能,你必须避免 Convert.ToByte
才能删除 SubString
.
Using Substring
is the best option in combination with Convert.ToByte
. See this answer for more information. If you need better performance, you must avoid Convert.ToByte
before you can drop SubString
.
这篇关于如何将字节数组转换为十六进制字符串,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!