現在、CRC 16 多項式を使用して文字の CRC を計算する CRC16 プログラムを作成していX^16 + X^15 + X^2 + 1
ます。プログラムは標準入力からデータを読み取り、16 ビットの CRC を 16 進数で出力する必要があります。それにもかかわらず、プログラムを実行すると、出力に間違った値が表示されます。
これが私のコードです:
#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
います。誰かが私が間違っていることを理解するのを手伝ってくれますか?