你怎么字节数组转换为十六进制的字符串,反之亦然? [英] How do you convert Byte Array to Hexadecimal String, and vice versa?

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

问题描述

这可能是在互联网上常见的问题,但我无法找到巧妙地解释了如何将字节数组转换为十六进制的字符串,反之亦然答案。

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屋!

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