C# 16进制与byte数组相互转换
/// <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)
{
????//将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;
}
|