C语言:
CRC-16 验证算法: ***************************************************************************
unsigned int CRC16_Checkout ( unsigned char *puchMsg, unsigned int usDataLen )
{
unsigned int i,j,crc_reg,check;
crc_reg = 0xFFFF;
for(i=0;i<usDataLen;i++)
{
crc_reg = (crc_reg>>8) ^ puchMsg[i];
for(j=0;j<8;j++)
{
check = crc_reg & 0x0001;
crc_reg >>= 1;
if(check==0x0001)
{
crc_reg ^= 0xA001;
}
}
}
return crc_reg;
}
示例:
##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5 ;CP=&&RtdInterval=30&&1C80\r\n,其中 1C08 为 CRC16 校验码,是对数据段 QN=20160801085857223; ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&& 进 行 CRC16 校验所得的校验码。
C#:
class Program
{
static void Main(string[] args)
{
string data = "QN=20160801085857223;ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&";
string crc = CRC16(System.Text.Encoding.UTF8.GetBytes(data));
Console.ReadKey();
}
public static string CRC16(byte[] data)
{
ushort crc = 0xFFFF;
int len = data.Length;
for (int i = 0; i < len; i++)
{
crc = (ushort)((crc >> 8) ^ data[i]);
for (int j = 0; j < 8; j++)
crc = (crc & 1) == 1 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
}
return string.Format("{0:X}", crc).PadLeft(4, '0');
}
}
来源: