PDA

View Full Version : Crc-16



Electrosolve
- 18th June 2013, 07:09
Hello

I'm using Darrel's CRC routine to calculate a CRC but the results are not as expected.

Here is Darrel's routine -


CRC VAR WORD
CRC_IN VAR BYTE
Idx VAR BYTE
CRC_Len CON 16
CRC_Poly CON $1021 ; x16 + x12 + x5 + 1

;-----CRC-16 -----------------------------------------------------
CRC16:
CRC.HighByte = CRC.HighByte ^ CRC_IN
FOR Idx = 0 to 7
IF CRC.0(CRC_Len-1) THEN
CRC = (CRC << 1) ^ CRC_Poly
ELSE
CRC = CRC << 1
ENDIF
NEXT Idx
RETURN


The eight bytes I'm using are "F2 AA 4C D4 60 F6 00 80"

The result I get is B2D5 rather than E23E as it should be.

Using an online calculator I get the same result, but if I tick the box "bit reflected", I get the correct result.

I'm sure I'm missing something really simple but I have tried many things without success.

Any Ideas?

Darrel Taylor
- 18th June 2013, 16:46
There are many variations of CRC16.
Along with the different polynomial ... Some need a starting value in the CRC variable, some need a final XOR of the CRC result with another value, some reverse the bit order of the data, and some use combinations of those methods.

The variation you are looking for is called CRC16_CCITT_TRUE or CRC16_KERMIT, which reverses the bit order.

For this type, the CRC16: code is the same.
But when you are feeding it data, reverse the order of each byte.
Then reverse the order of the final result.


ARRAYWRITE MyArray,[$F2,$AA,$4C,$D4,$60,$F6,$00,$80] ; Your Data


CRC = 0
FOR X = 0 TO 7
CRC_IN = MyArray(X) REV 8
GOSUB CRC16
NEXT X
CRC = CRC REV 16


The above gives the result ... $E23E

Electrosolve
- 18th June 2013, 17:11
Hello Darryl

Thank you for that. It now looks fine.

I did try reversing the bytes but didn't think about reversing the result, so I guess I was about halfway to solving it.

You have saved me a lot of time - thanks again.

BR

Reg Smith
:D