【发布时间】:2012-12-29 05:48:57
【问题描述】:
可能重复:
How do you convert Byte Array to Hexadecimal String, and vice versa?
我需要一种高效且快速的方法来进行这种转换。我尝试了两种不同的方法,但它们对我来说不够有效。对于具有大量数据的应用程序,还有其他快速方法可以实时完成此任务吗?
public byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length / 2).Select(x => Byte.Parse(hex.Substring(2 * x, 2), NumberStyles.HexNumber)).ToArray();
}
我觉得上面那个更有效率。
public static byte[] stringTobyte(string hexString)
{
try
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
catch
{
throw;
}
【问题讨论】:
-
另一个问题虽然表面上是关于双向转换,但最终集中在从字节到十六进制的转换上。这个问题是关于另一个方向的最佳转换,所以 FWIW,我认为它增加了一些东西。
-
这绝对不是重复的,因为它为所提供的特定问题提供了一组非常集中的答案