1、一位校验码生成
public static byte CRC(byte[] b)
{
//一号箱门55 01 a1 5f 00
string cmdString = null;
for (int i = 0; i < b.Length; i++)
{
cmdString += b[i].ToString("X").PadLeft(2, '0');
}
try
{
//CRC寄存器
int CRCCode = 0;
//将字符串拆分成为16进制字节数据然后两位两位进行异或校验
for (int i = 1; i < cmdString.Length / 2; i++)
{
string cmdHex = cmdString.Substring(i * 2, 2);
if (i == 1)
{
string cmdPrvHex = cmdString.Substring((i - 1) * 2, 2);
CRCCode = (byte)Convert.ToInt32(cmdPrvHex, 16) ^ (byte)Convert.ToInt32(cmdHex, 16);
}
else
{
CRCCode = (byte)CRCCode ^ (byte)Convert.ToInt32(cmdHex, 16);
}
}
return Convert.ToByte(CRCCode);//返回16进制校验码
}
catch
{
throw;
}
}
//int 转 byte[] 低字节在前(低字节序)
public static byte[] IntToByteArray(int n)
{
byte[] b = new byte[4];
b[0] = (byte)(n & 0xff);
b[1] = (byte)(n >> 8 & 0xff);
b[2] = (byte)(n >> 16 & 0xff);
b[3] = (byte)(n >> 24 & 0xff);
return b;
}
//int 转 byte[] 高字节在前(高字节序)
public static byte[] toHH(int n)
{
byte[] b = new byte[2];
b[1] = (byte)(n & 0xff);
b[0] = (byte)(n >> 8 & 0xff);
return b;
}
2、高低位校验码生成
/// <summary>
/// CRC校验,参数data为byte数组
/// </summary>
/// <param name="data">校验数据,字节数组</param>
/// <returns>字节0是高8位,字节1是低8位</returns>
public static byte[] CRC16(byte[] data)
{
//crc计算赋初始值
int crc = 0xffff;
for (int i = 0; i < data.Length; i++)
{
crc ^= data[i];
for (int j = 0; j < 8; j++)
{
int temp;
temp = crc & 1;
crc >>= 1;
crc &= 0x7fff;
if (temp == 1)
{
crc ^= 0xa001;
}
crc &= 0xffff;
}
}
//CRC寄存器的高低位进行互换
byte[] crc16 = new byte[2];
//CRC寄存器的高8位变成低8位,
crc16[1] = (byte)((crc >> 8) & 0xff);
//CRC寄存器的低8位变成高8位
crc16[0] = (byte)(crc & 0xff);
return crc16;
}
public static string AddCRC16(byte[] buffer)
{
byte[] crc16 = CRC16(buffer);
byte[] data = new byte[buffer.Length + 2];
for (int i = 0; i < buffer.Length; i++)
{
data[i] = buffer[i];
}
data[buffer.Length] = crc16[0];
data[buffer.Length + 1] = crc16[1];
//将十进制的data数组转换成16进制的数组
string str = string.Empty;
foreach (byte b in data)
{
str += $"{b:X2} ";
}
return str;
}