你怎么字节数组转换为十六进制的字符串,反之亦然? [英] How do you convert Byte Array to Hexadecimal String, and vice versa?
问题描述
这可能是在互联网上常见的问题,但我无法找到巧妙地解释了如何将字节数组转换为十六进制的字符串,反之亦然答案。
This is probably a common question over the Internet, but I couldn't find an answer that neatly explains how you can convert a byte array to a hexadecimal string, and vice versa.
推荐答案
或者:
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)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-","");
}
有这样做的,甚至更多的变种,例如<一个href=\"http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3928b8cb-3703-4672-8ccd-33718148d1e3/\">here.
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;
}
使用子串
是结合 Convert.ToByte
的最佳选择。请参见这个答案了解详情。如果你需要更好的性能,你必须避免 Convert.ToByte
之前,你可以删除子
。
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屋!