CRC  x8 + x2 + x + 1校验

参考:https://blog.csdn.net/liwei16611/article/details/86704451(这位大哥写的挺好的,大家可以优先学习)

手册中的参数定义:

本实验采用以上CRC标准。

#include <iostream>
using namespace std;
unsigned char  crc_8(unsigned char* const pstr,int length);
int main(){
//四组数据,前20字节为数据位,21位为CRC校验位
	unsigned char str[] = {0xA8,0xFF,0xFF,0xBE,0x00,0x00,0x01,0x00,0x00,0x76,0x00,0x2A,0x20,0x2A,0x40,0x2A,0x20,0x97,0x02,0x06,0xEA};
	unsigned char st2[] = {0xA8,0xFF,0xFF,0xBE,0x00,0x00,0x09,0x00,0x00,0x7B,0x00,0x2A,0x00,0x2A,0x60,0x2A,0x40,0x9B,0x02,0x07,0xB1};
	unsigned char st3[] = {0xA8,0xFF,0xFF,0x75,0xFF,0xFF,0xDC,0x00,0x00,0x99,0x00,0x2B,0x60,0x2B,0x80,0x2B,0x60,0xAD,0x02,0x07,0x38};
	unsigned char st4[] = {0xA8,0xFF,0xFF,0x7E,0xFF,0xFF,0xF9,0x00,0x00,0x7A,0x00,0x2C,0xC0,0x2C,0xC0,0x2C,0xC0,0xB7,0x02,0x07,0x49};
	if(crc_8(st3,20)  == 0x38){
		cout<<"true";
	}
	return 0;
} 

unsigned char  crc_8(unsigned char*  const pstr,int length){
	unsigned char* p= pstr;
	int len = length;
	unsigned char crc = 0xff;//根据自己实际情况或者手册中初值
	
	unsigned char i = 0;
	while(len--){
		crc ^= *p++;
		for(i = 8 ; i > 0 ; --i){
			if(crc & 0x80){					//判断最高位是不是为1 
				crc =  (crc << 1)^ 0x07; 	/* 最高位为1,不需要异或,往左移一位,然后与0x31异或 */
			}else{
				crc = (crc << 1); 
			} 
		} 
	} 
	return crc;
} 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值