有关CRC16的问题,请教!
下面是有关CRC16的算法,有几个问题不明白:
1 用01 05 03带进式中得到A5转换成十进制就是:165和188。但是标准答案 是: 91,12。转换成十进制就是145和18。不知错在那?
2 另外在程序中有个循环,但是好像循环体中并没有用到。
源代码如下:
#include <iostream.h>
unsigned short crc16(unsigned char cmd[3], int nByteCount);
void main()
{
unsigned short wcrcvalue=0;
unsigned char cmd[255];
cmd[1]=0x01;
cmd[2]=0x05;
cmd[3]=0x03;
wcrcvalue=crc16(cmd, 3);
cmd[4]=(wcrcvalue&0xff00)>>8;
cmd[5]=wcrcvalue&0x00ff;
cout<<(short)cmd[4]<<endl;
cout<<(short)cmd[5]<<endl;
cout<<wcrcvalue<<endl;
}
unsigned short crc16(unsigned char cmd[3], int nByteCount)
{
unsigned short wCrcValue = 0x0000;
while (nByteCount--)
{
for(int j=0;j<3;j++)
{
wCrcValue ^= cmd[j];
for (int i = 0; i < 8; i++)
{
if (wCrcValue & 1)
{
wCrcValue >>= 1;
wCrcValue ^= 0xa001;
}
else
{
wCrcValue >>= 1;
}
}
}
}
return wCrcValue;
}
希望各位多加指教,谢谢!