在C#中,常常需要16进制数组和string之间的相互转换,所以有以下两个函数,方便调用:
//字符串转16进制字节组:
public static byte[] strToHexByte(string hexString)
{
hexString = hexString.Replace(" ", ""); //去除空格
if ((hexString.Length % 2) != 0) //判断hexstring的长度是否为偶数
{
hexString += "";
}
//声明一个长度为hexstring长度一半的字节组returnBytes
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
{
//将hexstring的两个字符转换成16进制的字节组
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return returnBytes;
}
//字节组转换成16进制的字符串:
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2"); //byte转16进制字符
}
}
return returnStr;
}