且构网

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

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

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

要么:

  public static string ByteArrayToString(byte [] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2 );
foreach(ba中的字节b)
hex.AppendFormat({0:x2},b);
return hex.ToString();

或者:

{
返回BitConverter.ToString(ba).Replace( - ,);
}

还有更多的变体,比如 here



反向转换将如下所示:

  public static byte [] StringToByteArray(String十六进制)
{
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);
返回字节;






使用 Substring 是与 Convert.ToByte 组合的***选择。有关更多信息,请参阅此答案。如果您需要更好的性能,您必须先避免 Convert.ToByte ,然后才能删除 SubString


How can you convert a byte array to a hexadecimal string, and vice versa?

Either:

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();
}

or:

public static string ByteArrayToString(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-","");
}

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

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;
}


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.