CRC16 串口校验

 

近期对接客户 利用串口通信,其中要用到CRC-IBM 8005 校验方式,网上搜寻好久,就是对不上计算器算出来的结果,最后通过一个国外的开源CRC代码,自己扣取成功:

先贴上 代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>


#define		CRC_POLY_SICK		0x8005
#define		CRC_START_SICK		0x0000


unsigned short crc_sick( const unsigned char *input_str, size_t num_bytes ) {

	unsigned short crc;
	unsigned short low_byte;
	unsigned short high_byte;
	
	unsigned short short_c;
	unsigned short short_p;
	
	int a;
	crc     = CRC_START_SICK;
	short_p = 0;
	for (a=0; a<num_bytes; a++) {
	
		printf("input_str[a] is %x\n",input_str[a]);
		
		
		short_c = 0x00ff & (unsigned short) input_str[a];

		if ( crc & 0x8000 ) crc = ( crc << 1 ) ^ CRC_POLY_SICK;
		else                crc =   crc << 1;

		crc    ^= ( short_c | short_p );
		short_p = short_c << 8;	
	}
	
	low_byte  = (crc & 0xff00) >> 8;
	high_byte = (crc & 0x00ff) << 8;
	crc       = low_byte | high_byte;
	
	printf("low_byte:0x%x;high_byte:0x%x \n",low_byte,high_byte);
	
	
	return crc;

}  /* crc_sick */





// AA 00 00 0B 0B 01 00 00

int main()
{
	unsigned char protocol_buffer_open_wifi[8]  = {0xAA,0x00,0x00,0x0B,0x0B,0x01,0x00,0x00};
	
	unsigned short crc_val = crc_sick(protocol_buffer_open_wifi, 8);
	unsigned char CRChi =  (unsigned char)(crc_val >> 8); //高八位
	unsigned char CRClo =  (unsigned char)crc_val;
	printf("CRChi:0x%x   CRClo:0x%x \n",CRChi,CRClo);
	
	
	
	return 0;
}

  

但这只是IBM的8005标准,其他标准可以下载源码移植:

 

在线 计算 全套CRC 工具:https://www.lammertbies.nl/comm/info/nl_crc-calculation.html

全套CRC开源代码下载:https://www.libcrc.org/

 

验证结果:

 

 

 

(高低位反了,记得更换下)

 

转载于:https://www.cnblogs.com/hongzhunzhun/p/7405439.html

### CRC16 8005 查表实现 CRC16 8005 是一种常见的循环冗余校验算法,其多项式为 `0x8005`。为了提高计算效率,通常会预先构建一个查找表 (lookup table),该表存储了所有可能字节值对应的 CRC 值。 #### 构建 Lookup Table 根据 Sarwate 的方法,在 1988 年提出的使用查找表来加速 CRC 计算的方式[^3],可以通过预计算每个可能输入字节的结果并将其存储在一个数组中。以下是 Python 实现: ```python def create_crc16_table(): polynomial = 0x8005 crc_table = [] for i in range(256): crc = i << 8 for j in range(8): if crc & 0x8000: crc = (crc << 1) ^ polynomial else: crc <<= 1 crc &= 0xFFFF crc_table.append(crc) return crc_table ``` 此函数创建了一个长度为 256 的列表 `crc_table`,其中每一项代表当输入特定字节时所得到的 CRC 结果。 #### 使用 Lookup Table 进行 CRC16 8005 计算 有了上述表格之后,就可以利用它来进行高效的 CRC16 8005 计算了。下面是一个基于之前生成的查找表执行 CRC16 8005 校验的例子: ```python def calculate_crc16_8005(data, crc=0xFFFF, crc_table=None): if not crc_table: crc_table = create_crc16_table() for byte in data: t = ((crc >> 8) ^ byte) & 0xFF crc = (((crc << 8) & 0xFFFF) ^ crc_table[t]) & 0xFFFF return crc ``` 这段代码接收待检验的数据序列作为参数,并返回最终计算出来的 CRC16 8005 值。注意这里采用了与给定公式一致的操作方式更新 CRC 变量[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值