public static byte[] HexToByte(string msg)
{
msg = msg.Replace(" ", "");//移除空格
if (msg.Length < 2)
{
return new byte[] { (byte)Convert.ToByte(msg.PadLeft(2,'0'), 16) };
}
//create a byte array the length of the
//divided by 2 (Hex is 2 characters in length)
byte[] comBuffer = new byte[msg.Length / 2];
for (int i = 0; i < msg.Length; i += 2)
{
if (msg.Length >= i + 2)
{
//convert each set of 2 characters to a byte and add to the array
comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
}
else
{
comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, msg.Length-i).PadLeft(2, '0'), 16);
}
}
return comBuffer;
}
c# HexToByte修复版
最新推荐文章于 2024-04-30 21:44:02 发布