一、累加和取反加一
1 /* 2 * 取反加一原理: 3 * 0xFE(0b11111110) 4 * 取反得0x01(0b00000001) 5 * 二者相加得0xFF(0b11111111) 6 * 再加一得0x00(0b00000000) 7 **/ 8 /// <summary> 9 /// 发送端和校验函数,与CheckSume_Rx配合使用 10 /// </summary> 11 /// <param name="buf"></数据缓冲区指针> 12 /// <param name="len"></数据缓冲区长度> 13 /// <returns></校验和取反> 14 unsigned char CheckSume_Tx(const unsigned char* buf, int len) 15 { 16 unsigned char ret = 0, i; 17 for (i = 0; i < len; ++i) 18 { 19 ret += *buf++; 20 } 21 return ~ret; 22 } 23 24 /// <summary> 25 /// 接收端和校验函数,与CheckSume_Tx配合使用 26 /// </summary> 27 /// <param name="buf"></数据缓冲区指针> 28 /// <param name="len"></数据缓冲区长度,此长度比发送缓冲区长度大1,因为包含发送来的校验和取反> 29 /// <returns></0则成功,非0失败> 30 unsigned char CheckSume_Rx(const unsigned char* buf, int len) 31 { 32 unsigned char ret = 0, i; 33 for (i = 0; i < len; ++i) 34 { 35 ret += *buf++; 36 } 37 ret += 1; 38 //如果返回值为0,则表示校验成功。不为0则失败 39 return ret; 40 }
二、累加和相等
1 /// <summary> 2 /// 计算校验和,发送接收两端计算校验和相等则校验成功 3 /// </summary> 4 /// <param name="buf"></数据缓冲区指针> 5 /// <param name="len"></数据缓冲区长度> 6 /// <returns></校验和> 7 unsigned char CheckSume(const unsigned char* buf, int len) 8 { 9 unsigned char ret = 0, i; 10 for (i = 0; i < len; ++i) 11 { 12 ret += *buf++; 13 } 14 return ret; 15 }
标签:和校验,++,unsigned,ret,char,传输,len,串口,buf From: https://www.cnblogs.com/GREEN-FIEID/p/17177843.html