【发布时间】:2016-11-06 15:35:45
【问题描述】:
我正在 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
现在的问题是...如果我在第一次比较后更改初始值,它将始终等于数据流。
例如:如果我得到初始值是
1011 0000 1011 0101
和数据流
0011 0110 1000 0101
第一次迭代后。
它们总是相等的,因为开头的0's 无关紧要,可以忽略。
在下一次迭代之后,它们将是:
011 0000 1011 0101
和数据流分别
011 0110 1000 0101
但0's 可以再次被忽略,我们得到平等。
我真的很困惑。
这是我的 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++;
}
【问题讨论】:
-
你确定在同一个表达式中混合
&和&&时的优先级吗? -
crc & 1 && data & 1是错误的。根据“如果数据的第一位不等于初始值的第一位”应该是crc & 1 == data & 1。如果你真的想用逻辑运算符来做,应该是xor (not) -
这甚至不会编译。
data是一个数组,但您正在执行data & 1和data++之类的操作。 -
@EugeneSh。您的建议将编译为
crc & (1 == data) & 1 -
@WeatherVane 对。应始终咨询this。印象中按位运算符与算术运算符属于同一组...