且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字节数组转换为十六进制字符串,反之亦然?

更新时间:2022-12-07 17:06:40

您可以使用 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.