C# 16进制字符串和Byte数组互转帮助类
C# 16进制字符串和Byte数组互转帮助类
最近开发上位机程序主要负责和下位机通信,为了方便拿测试指令数据测试,需要将厂家给的demo数据直接拿程序进行测试,做下记录后期复用。
/// <summary>
/// 16进制和数组互转帮助类
/// </summary>
class ByteHelper
{
/// <summary>
/// byte数组转16进制字符串
/// </summary>
/// <param name="data">byte数组</param>
/// <returns></returns>
public static string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
{
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
}
return sb.ToString().ToUpper();
}
/// <summary>
/// 16进制字符串转byte数组
/// </summary>
/// <param name="hexString">16进制字符</param>
/// <returns></returns>
public static byte[] ByteArrayToHexString(string hexString,string spiltChar=" ")
{
if (!string.IsNullOrEmpty(spiltChar))
{
hexString = hexString.Replace(spiltChar,"");
}
//将16进制秘钥转成字节数组
var byteArray = new byte[hexString.Length / 2];
for (var x = 0; x < byteArray.Length; x++)
{
var i = Convert.ToInt32(hexString.Substring(x * 2, 2), 16);
byteArray[x] = (byte)i;
}
return byteArray;
}
}