How to calculate CRC using this code?

I am trying to get a radio connection between a device and my server. The data from the device is as follows:

fa-00-01-09-16-aa-00-14-10-01-01-00-01-16-ff-ff-ff-ff-ff-ff-cb-14 

where are the last two bytes of CRC. Now I need to send a response to my device and calculate its CRC. The device data packet does not say much, and it only provides the C function for computing it, but I can hardly understand what I should apply for this function.

 unsigned int CRC_Check(unsigned char *ucCRC_Buf, unsigned char ucBufLength) { unsigned int uiX, uiY, uiCRC; unsigned char ucStart = 0; uiCRC = 0xFFFF; //set all 1 if (ucBufLength <= 0 || ucStart > ucBufLength) { uiCRC = 0; } else { ucBufLength += ucStart; for (uiX = (unsigned int)ucStart; uiX < ucBufLength; uiX++) { uiCRC = (unsigned int)(uiCRC ^ ucCRC_Buf[uiX]); for (uiY = 0; uiY <= 7; uiY++) { if((uiCRC & 1) != 0) uiCRC = (unsigned int)((uiCRC >> 1)^0xA001); else uiCRC = (unsigned int)(uiCRC >> 1); } } } return uiCRC; } 

The data sheet also says: β€œCRC verification is performed in the data packet, excluding the start code and verification code”, which means the first byte (0xFA) and the last two bytes (CRC).

Now I'm trying to figure out what it expects as unsigned char *ucCRC_Buf and unsigned char ucBufLength . From my point of view, I try:

 unsigned int crc = CRC_Check("00010916aa0014100101000116ffffffffffff",38); printf("%d\n", crc); 

What is the line like at the beginning (without the first and last two bytes), and I expect CB14 (hex). But it gives a different number (54016 (dec), which is equal to D300 (hex)).

Any idea what I'm doing wrong?

+5
source share
2 answers

Perhaps you need to pass the bytes themselves, not their hexadecimal representation.

Change

 unsigned int crc=CRC_Check("00010916aa0014100101000116ffffffffffff",38); 

to

 unsigned int crc=CRC_Check("\x00\x01\x09\x16\xaa\x00\x14\x10\x01\x01\x00\x01\x16\xff\xff\xff\xff\xff\xff", 19); 

Please note that only 19 bytes. (Thanks @alk)

+6
source

The data server is accepted in Hexadecimal format.

You are passing a string to a function that gives incorrect results.

The correct way to check:

 unsigned char data[] = {0x00,0x01,0x09,0x16,0xaa,0x00,0x14,0x10,0x01,0x01,0x00,0x01,0x16,0xff,0xff,0xff,0xff,0xff,0xff} unsigned int CRC = CRC_Check(&data[0],19); 
+2
source

Source: https://habr.com/ru/post/1270886/


All Articles