checksum校验
//检验校验码 加和, 2byte校验码
int Checksum_Check(unsigned char *buf, int len)
{
int b = 0;
uint32_t temp1=0;
uint16_t temp;
for(int i=0; i<len-2; i++)
temp1 += buf[i];
temp = (uint16_t)temp1;
unsigned char *p = (unsigned char *)&temp;
if((p[0] == buf[len-2]) && (p[1] == buf[len-1]))
b = 1;
return b;
}
//填入校验码 最后2个byte为校验码, len包括校验码
void Checksum_Fill(unsigned char *buf, int len)
{
int i;
uint16_t check = 0;
if(len < 3)
return;
for(i=0; i<len-2; i++)
check += buf[i];
buf[len-2] = check & 0x00ff;
buf[len-1] = (check & 0xff00) >> 8;
}
//计算校验码 2字节加和
uint16_t Checksum_Cal(unsigned char *buf, int len)
{
uint16_t check = 0;
for(int i=0; i<len; i++)
check += buf[i];
return check;
}
crc校验计算
//-----------------------------------------------------------------------------------
//CRC计算
//输入参数1:snd,待校验的字节数组名
//输入参数2:num,待校验的字节总数(包括CRC校验的2个字节)
//函数返回值:校验失败时返回非0值。校验成功返回0。
//------------------------------------------------------------------------------------
unsigned int calc_crc16(unsigned char *snd,unsigned char num)
{
unsigned char i, j;
unsigned int c,crc=0xFFFF;
for(i = 0; i < num; i ++)
{
c = snd[i] & 0x00FF;
crc ^= c;
for(j = 0;j < 8; j ++)
{
if (crc & 0x0001)
{
crc>>=1;
crc^=0xA001;
}
else
{
crc>>=1;
}
}
}
return(crc);
}