如何将字节数组转换为十六进制字符串,反之亦然? [英] How do you convert a byte array to a hexadecimal string, and vice versa?

查看:120
本文介绍了如何将字节数组转换为十六进制字符串,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

要么:

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

或者:

<$公共静态字符串ByteArrayToString(byte [] ba)
{
返回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.

这篇关于如何将字节数组转换为十六进制字符串,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆