CRC calculation

I am trying to interact with a third-party system, and they provided a sample code to calculate the CRC value when sending text data.

The C code provided by the provider is as follows:

#define CRCRES 0xf0b8 /* residue for good verify */ #define DEBUG unsigned crctbl[] = {0x0000, 0x1081, 0x2102, 0x3183, 0x4204, 0x5285, 0x6306, 0x7387, 0x8408, 0x9489, 0xa50a, 0xb58b, 0xc60c, 0xd68d, 0xe70e, 0xf78f}; /* * This uses a 32 byte table to lookup the crc 4 bits at a time. * The CRC CCITT is used. */ unsigned short calc_crc(unsigned char *ptr, unsigned length) { unsigned short crc; unsigned short i; unsigned char pos,ch; crc = 0xffff; /* precondition crc */ for (i = 0; i < length; i++,ptr++) { ch = *ptr; pos = (crc ^ ch) & 15; crc = ((crc >> 4) & 0x0fff) ^ crctbl[pos]; ch >>= 4; pos = (crc^ch) & 15; crc = ((crc >> 4) & 0xffff) ^ crctbl[pos]; } crc = ~crc; /* post condition */ crc = (crc << 8) | (crc >> 8); /* bytewise reverse */ return crc; } /* * tests the block of code containing the crc to verify it * content. This compares to the reversed and inverted * residue. */ int test_crc(unsigned char *ptr, unsigned length) { unsigned short crc; unsigned char arr [] = {'X','Y','Z'}; crc = calc_crc(arr,3); printf("Calced crc of test to be %04x, (should be 470f)\n", crc); return (crc == 0x470f); } 

I copied this code and put the sample program in C. The test_crc method does not calculate CRC as 470f (its calculation as DD7A).

I hope someone can verify that this code is not working, as the seller says it should or helped me return test_crc to the correct value.

Thanks for the help.

+4
source share
3 answers

The problem is resolved. The specifications from the vendor were incorrect. The correct checksum for XYZ is DD7A. The documentation was wrong.

Add this to the fact that the page earlier, when they explain what data is passed to the calc_crc method to get crc for the actual message, is also incorrect, which made it a difficult project.

Thanks for the help.

+4
source

Calculation, as they say, does not show any error that comes to my mind. Just repeat the algorithm. In particular, when looking for possible problems, pay attention to the fact that the constants located in different parts of the algorithm are 0x0fff and 0xffff . Maybe it should be 0x0fff and 0xfff0 more symmetrical ... Sometimes we think that the real problem can arise from another place and forget to double-check the obvious things ... :)

+3
source

Are hardware platforms the same? Maybe you have different endianness ? (For example, you have x86 they have 68,000 cpu.)

+2
source

All Articles