我正在开发一个库,通过RS232或RS485连接提供简单可靠的通信.此代码的一部分涉及对数据使用CRC16校验和来检测线路噪声的损坏.我已经创建了一个计算CRC16校验和的函数,但它似乎没有输出正确的值.
我写的相关代码如下(也可以在这里找到).
#include <stdint.h>
#define CRC16 0x8005
uint16_t gen_crc16(const uint8_t *data, uint16_t size)
{
uint16_t out = 0;
int bits_read = 0, bit_flag;
/* Sanity check: */
if(data == NULL)
return 0;
while(size > 0)
{
bit_flag = out >> 15;
/* Get next bit: */
out <<= 1;
out |= (*data >> (7 - bits_read)) & 1;
/* Increment bit counter: */
bits_read++;
if(bits_read > 7)
{
bits_read = 0;
data++;
size--;
}
/* Cycle check: */ …
Run Code Online (Sandbox Code Playgroud)