#define P_CCITT 0x1021
static int crc_tabccitt_init = FALSE;
static unsigned short crc_tabccitt[256];
static void init_crcccitt_tab( void )
{
int i, j;
unsigned short crc, c;
for (i=0; i<256; i++)
{
crc = 0;
c = ((unsigned short) i) << 8;
for (j=0; j<8; j++)
{
if ( (crc ^ c) & 0x8000 ) crc = ( crc << 1 ) ^ P_CCITT;
else crc = crc << 1;
c = c << 1;
}
crc_tabccitt[i] = crc;
}
crc_tabccitt_init = TRUE;
} /* init_crcccitt_tab */
unsigned short update_crc_ccitt( unsigned short crc, char c ) {
unsigned short tmp, short_c;
short_c = 0x00ff & (unsigned short) c;
if ( ! crc_tabccitt_init )
init_crcccitt_tab();
tmp = (crc >> 8) ^ short_c;
crc = (crc << 8) ^ crc_tabccitt[tmp];
return crc;
}
char input_string[20]="000311r";
char *ptr, *dest, hex_val, prev_byte;
unsigned short crc_ccitt_ffff;
ptr = input_string;
dest = input_string;
while( *ptr && *ptr != 'r' && *ptr != 'n' )
{
if ( *ptr >= '0' && *ptr <= '9' ) *dest++ = (char) ( (*ptr) - '0' );
if ( *ptr >= 'A' && *ptr <= 'F' ) *dest++ = (char) ( (*ptr) - 'A' + 10 );
if ( *ptr >= 'a' && *ptr <= 'f' ) *dest++ = (char) ( (*ptr) - 'a' + 10 );
ptr++;
}
* dest = 'x80';
*(dest+1) = 'x80';
crc_ccitt_ffff = 0xffff;
prev_byte = 0;
ptr = input_string;
while ( *ptr != 'x80' )
{
hex_val = (char) ( ( * ptr & 'x0f' ) << 4 );
hex_val |= (char) ( ( *(ptr+1) & 'x0f' ) );
crc_ccitt_ffff = update_crc_ccitt( crc_ccitt_ffff, hex_val );
prev_byte = hex_val;
ptr += 2;
}
//input_string[0] = 0;
printf( "CRC-CCITT (0xffff) = 0x%04Xn", crc_ccitt_ffff
);
return 0;