简介:
在通信领域(上下位机、某些部件之间)的一些通信协议protocol中,使用LRC进行简单的累加和校验;
如果有必要或者是芯片速度高,可以采用更复杂的CRC校验;
实用范围:
1, 通信协议传输校验;
2, 以ASCII进行传输;
//return one byte
#include <stdio.h>
#include <string.h>
#define CHECK_PARAM 0
unsigned char
check_LRC(const char *buf, unsigned int len)
{
unsigned char chksum = 0; //checksum init
#if CHECK_PARAM
if (NULL == buf)
{
return 0;
}
if (len > strlen(buf))
{
printf("len is long, out of the buf range!\n");
return 0;
}
#endif
for (; len > 0; len--)
{
chksum -= *buf++;
}
return chksum;
}
说明:1, 如果我们能够在输入的时候保证参数的正确性,可以把参数检测注释掉,不检测空buf指针和防止缓冲区溢出检测;
2, 感觉这样写,应该能够达到检测协议传输正确性的目的,并且能够非常快速的完成;