分类: C/C++
2013-03-04 10:57:58
#include "stdio.h"
unsigned short crc16a(unsigned char *buf, int length)
{
unsigned char crc_reg[16];
unsigned char data[1024];
unsigned short crc_ret;
int i;
int j;
int n;
unsigned char reg1;
unsigned char reg2;
unsigned char reg3;
for(i=0;i<16;i++)
{
crc_reg[i]=0;
}
for(i=0; i
n = i * 8;
for(j=0; j<8; j++)
{
if((buf[i] & 0x80>>j))
{
data[n+j] = 1;
}
else
{
data[n+j] = 0;
}
}
}
for(i=0; i
reg1 = data[i] ^ crc_reg[15];
reg2 = reg1 ^ crc_reg[1];
reg3 = reg1 ^ crc_reg[14];
crc_reg[1] = crc_reg[0];
for(j=14; j>=3; j--)
{
crc_reg[j] = crc_reg[j-1];
}
crc_reg[0] = reg1;
crc_reg[2] = reg2;
crc_reg[15] = reg3;
}
#if 1
for(i=0;i<16;i++){
printf("%x\t", crc_reg[i]);
}
#endif
crc_ret = 0;
for(i=15;i>=0;i--)
{
if(crc_reg[i]==0){
crc_ret = crc_ret << 1;
}
else
{
crc_ret = crc_ret << 1 | 1;
}
}
return crc_ret;
}
int main(int argc, char* argv[])
{
unsigned char m_data[127];
int i;
unsigned short crc;
for(i=0;i<125;i++)
{
m_data[i] = i;
}
m_data[125] = 0xe9;
m_data[126] = 0xcf;
crc = crc16a((unsigned char*)m_data, 125);
printf("crc_ret = 0x%x\n",crc);
return 0;
}