【发布时间】:2021-06-13 16:27:40
【问题描述】:
我有一个使用 CRC-16 计算字符 CRC 的程序。程序如下。
#include<stdio.h>
#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;
// test
printf("buffer in function %s\n", data);
/* Sanity check: */
if(data == NULL)
return 0;
while(size > 0)
{
bit_flag = out >> 15;
/* Get next bit: */
out <<= 1;
out |= (*data >> bits_read) & 1; // item a) work from the least significant bits
/* Increment bit counter: */
bits_read++;
if(bits_read > 7)
{
bits_read = 0;
data++;
size--;
}
/* Cycle check: */
if(bit_flag)
out ^= CRC16;
}
// item b) "push out" the last 16 bits
int i;
for (i = 0; i < 16; ++i) {
bit_flag = out >> 15;
out <<= 1;
if(bit_flag)
out ^= CRC16;
}
// item c) reverse the bits
uint16_t crc = 0;
i = 0x8000;
int j = 0x0001;
for (; i != 0; i >>=1, j <<= 1) {
if (i & out) crc |= j;
}
return crc;
}
int main()
{
char buf[]="123456789";
int c , r;
printf ("the buf has %s", buf);
r = gen_crc16(buf,sizeof(buf)-1);
printf("%04hx\n", r);
return (0);
}
问题: 我正在尝试修改此代码,以便可以在输入数据的末尾附加返回的 CRC 值并再次调用函数 gen_crc()。 gen_crc() 函数这次应该返回 0。
目前还没有得到任何帮助或建议,欢迎。我是初学者
The above C program is taken as a reference from the earlier StackOverflow post
【问题讨论】:
-
I want to modify this code首先让它易于阅读。正确格式化。