简体   繁体   English

CRC算法实现

[英]CRC algorithm implementation

I'm implementing an CRC16 algorithm in C which is: 我正在C中实现CRC16算法,它是:

init = 0x0000 as long as the data stream goes on if the first bit of data is not equal to the first bit of initial value init = leftshift init once and xor it with the polynomial otherwise leftshift init go to the next data bit init = CRC Checksum

Now the problem is... If I change the init value after the first comparison it's gonna always be equal to the data stream. 现在的问题是...如果在第一次比较后更改init值,它将始终等于数据流。

For example: If I get the initial value to be 例如:如果我得到的初始值为

1011 0000 1011 0101

and the data stream 和数据流

0011 0110 1000 0101

after first iteration. 在第一次迭代之后。

They are going to always be equal, since the 0's at the beginning do not matter, and can be ignored. 它们将始终相等,因为开头的0's无关紧要,可以忽略。

And after the next iteration they are going to be: 在下一次迭代之后,它们将是:

011 0000 1011 0101

and data stream respectively 和数据流分别

011 0110 1000 0101

but again the 0's can be ignored and we get equality. 但是再次可以忽略0's ,我们得到相等。

I'm really confused. 我真的很困惑

Here's my C code: 这是我的C代码:

#define POLY 0x8005

int crc = 0x0000;   // Initial value
char data[1024];
int *dp = data;
int fd, nread;

fd = open(argv[1], O_RDWR);
nread = read(fd, data, sizeof(data));
int *end = dp + nread;



while(data < end)
{
    crc = crc & 1 && data & 1 ? crc << 1 : (crc << 1) ^ POLY;
    data++;
}

Several issues: 几个问题:

  1. You're operating on the least significant bit but should be working on the most significant bit. 您正在最低有效位上进行操作,但应该在最高有效位上进行操作。 This may be what's causing your confusion regarding bits staying the same, since you're looking at the wrong end of the values. 这可能是造成您对位保持不变的困惑的原因,因为您查看的是错误的值结尾。

  2. crc & 1 && data & 1 checks that the bits are equal to 1 instead of checking that they are equal to each other. crc & 1 && data & 1检查这些位等于1,而不是检查它们是否相等。

  3. You seem to be confused on whether data is an array (as declared), an integer (as used in data & 1 ), or a pointer (as used in data++ ). 您似乎对data是数组(声明的),整数(在data & 1 )还是指针(在data++ )感到困惑。

  4. If you change data to a pointer and increment it by 1 at each step, that would mean that you are only processing one bit from each input byte. 如果将data更改为指针并在每一步将其递增1,则意味着您仅在每个输入字节中处理一位。 You need an inner loop to process all 8 bits. 您需要一个内部循环来处理所有8位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM