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/

 

验证结果:

 

 

 

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

 

posted @ 2017-08-21 17:03  慢伴拍的二叉树  阅读(2036)  评论(0编辑  收藏  举报