分类
设计开发

一种CRC代码生成工具

在数据通讯领域,为了保证数据的正确,就不得不采用检错的手段,CRC是最常见的一种,它的有长度8位,16位,32位的各种生成多项式,输入和输出还可能翻转,可以直接bit操作或表驱动进行编解码,手工编写编解码程序不但繁琐,而且容易出错。
pycrc是一种基于python的CRC嵌入C代码生成器,它下载链接
https://pycrc.org/, 它可以直接输出符合C89, ANSI, C99的C代码,它是一个命令行工具,下面是它的一些常见选项

选项说明
--width=NUMuse NUM bits in the Polynomial
--poly=HEXuse HEX as Polynomial
-reflect-in=BOOLreflect the octets in the input message
xor-in=HEXuse HEX as initial value
--reflect-out=BOOLreflect the resulting checksum before applying the XorOut
--xor-out=HEXxor the final CRC value with HEX
--algorithm=ALGOchoose an algorithm from {bit-by-bit, bbb, bit-by-bit-fast, bbf, table-driven, tbl, all}

生成接口

typedef uint16_t crc_t;

typedef uint16_t crc_t;

crc_t crc_init( void);

crc_t crc_update( crc_t crc,
const unsigned char *data,
size_t data_len);

crc_t crc_finalize( crc_t crc);

使用示例

#include “pycrc_generated_crc.h”
#include <stdio.h>

int main(void)
{

static const unsigned char str1[] = "1234";
static const unsigned char str2[] = "56789";
crc_t crc;

crc = crc_init();
crc = crc_update(crc, str1, sizeof(str1) - 1);
crc = crc_update(crc, str2, sizeof(str2) - 1);
/* more calls to crc_update... */
crc = crc_finalize(crc);

printf("0x%lx\n", (long)crc);
return 0;

}

在线CRC计算器

https://crccalc.com/