http://blog.chinaunix.net/uid-20416869-id-173134.html 随便找的博客地址,别人的
unsigned short do_crc(unsigned char *message, unsigned int len)
{
int i, j;
unsigned short crc_reg;
crc_reg = (message[0] << 8) + message[1];
for (i = 0; i < len; i++)
{
if (i < len - 2)
for (j = 0; j <= 7; j++)
{
if ((short)crc_reg < 0)
crc_reg = ((crc_reg << 1) + (message[i + 2] >> (7 - i))) ^ 0x1021;
else
crc_reg = (crc_reg << 1) + (message[i + 2] >> (7 - i));
}
else
for (j = 0; j <= 7; j++)
{
if ((short)crc_reg < 0)
crc_reg = (crc_reg << 1) ^ 0x1021;
else
crc_reg <<= 1;
}
}
return crc_reg;
}
显然,每次内循环的行为取决于寄存器首位。由于异或运算满足交换率和结合律,以及与0异或无影响,消息可以不移入寄存器,而在每次内循环的时候,寄存器首位再与对应的消息位异或。改进的代码如下:
unsigned short do_crc(unsigned char *message, unsigned int len)
{
int i, j;
unsigned short crc_reg = 0;
unsigned short current;
for (i = 0; i < len; i++)
{
current = message[i] << 8;
for (j = 0; j < 8; j++)
{
if ((short)(crc_reg ^ current) < 0)
crc_reg = (crc_reg << 1) ^ 0x1021;
else
crc_reg <<= 1;
current <<= 1;
}
}
return crc_reg;
}
上面那个程序搞懂了,下面那个看不懂啊,怎么变成那样的!?帮我看看吧谢谢了!