我目前正在寫一個CRC16程序,它使用CRC 16多項式計算CRC字符X^16 + X^15 + X^2 + 1
。程序應該從標準輸入讀取數據,並以十六進制輸出16位CRC。儘管如此,當我執行程序時,我得到了錯誤的輸出值。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));
}
輸出:
(我讀123456789我的txt文件)
./crc1 < testfile.txt
123456789
7bda
它應該是BB3D
,但我得到7bda
。有人能幫我弄清楚我做錯了什麼嗎?
在'的buf [計數++] =的putchar(C)',第一個字節是在'BUF [-1] ' –
測試'if(argc <1)'是無用的,因爲在所有(託管)系統中,'argc'至少是'1'。 –
所以我應該從0開始buf – zer0