上位机(C# / JAVA)CRC16校验程序
/// <summary>
/// calculate CRC
/// </summary>
/// <param name="modbusdata">Source data address</param>
/// <param name="length">data length</param>
/// <returns></returns>
private int crc16_modbus(byte[] modbusdata, int length)
{
int i, j;
int crc = 0xffff; //0xffff or 0
try
{
for (i = 0; i < length; i++)
{
crc ^= modbusdata[i]&0xff;
for (j = 0; j < 8; j++)
{
if ((crc & 0x01) == 1)
{
crc = (crc >> 1) ^ 0xa001;
}
else
{
crc >>= 1;
}
}
}
}
catch (Exception)
{
throw;
}
return crc;
}
/// <summary>
///
/// </summary>
/// <param name="modbusdata"></param>
/// <param name="length"></param>
/// <returns></returns>
private int crc16_flage(byte[] modbusdata, int length)
{
int Receive_CRC = 0, calculation = 0;//接收到的CRC,计算的CRC
if(length<=2) return 0;
Receive_CRC = crc16_modbus(modbusdata, length-2);
calculation = modbusdata[length -2];
calculation <<= 8;
calculation += modbusdata[length-1];
if (calculation != Receive_CRC)
{
return 0;
}
return 1;
}
注:对于上位机byte类型需要&0xff
|