我目前正在编写一个 CRC16 程序,它使用 CRC 16 polynomial 计算字符的 CRC X^16 + X^15 + X^2 + 1
。程序应该从标准输入读取数据并以十六进制输出 16 位 CRC。尽管如此,当我执行程序时,我得到了错误的输出值。
这是我的代码:
#include <stdint.h>
#define CRC16 0x8005
unsigned short crc(unsigned char msg[], int len)
{
unsigned short out = 0;
int bits = 0, t_flag;
int x = 0;
/* Sanity check: */
if(msg == NULL)
return 0;
while(len > x)
{
unsigned short data = msg[x];
t_flag = out >> 15;
/* Get next bit: */
out <<= 1;
out |= (data >> bits) & 1; // item a) work from the least significant bits
/* Increment bit counter: */
bits++;
if(bits > 7)
{
bits = 0;
data++;
len--;
}
/* Cycle check: */
if(t_flag)
out ^= CRC16;
}
// item b) "push out" the last 16 bits
int i;
for (i = 0; i < 16; ++i) {
t_flag = out >> 15;
out <<= 1;
if(t_flag)
out ^= CRC16;
}
// item c) reverse the bits
unsigned short crc1 = 0;
i = 0x8000;
int j = 0x0001;
for (; i != 0; i >>=1, j <<= 1) {
if (i & out) crc1 |= j;
}
return crc1;
}
int main (int argc, char *argv[]) {
//if (argv[1] == "trace") {
//printf(argv[1]);
//}
char ARGV;
if(argc < 1) {
printf("Must have atleast one arguments\n");
return 1;
}
char buf[256];
int c , r;
int count = -1;
while((c = getchar())!=EOF) {
buf[count++] = putchar(c);
}
r = crc(buf, count);
//printf("%s\n",argv[1] );
printf("%04hx\n", r);
//print("%x\n", argv[1]);
return (0);
//printf(" %4x\n", crc(argv[1], 16));
}
输出:
(我在我的 txt 文件中阅读 123456789)
./crc1 < testfile.txt
123456789
7bda
应该是,BB3D
但我得到了7bda
。有人可以帮我弄清楚我做错了什么吗?