' BASIC ROUTINE TO CALCULATE CRC16-CCITT ' WAGNER LIPNHARSKI - NOV/1999 - HTTP://WWW.USTR.NET ' ' A = 16 bits counter - CRC16 CCITT - Accumulator result. ' A should be preset to ZERO at the start. ' C = 8 Bits processing byte, value from zero to 255. ' After processing all "C" bytes, A value should be ' converted to Hex and have bytes inverted, ' ' A$ = "0000" + HEX$(A) ' A$ = RIGHT$(A$,4) ' A$ = RIGHT$(A$,2)+LEFT$(A$,2) ' A1 = VAL(LEFT$(A$,2)) ' A2 = VAL(RIGHT$(A$,2)) ' A1$ = CHR$(A1) ' A2$ = CHR$(A2) ' ' Transmit A1$, then A2$, as the CRC bytes. ' ' For testing purposes, processing 10 bytes values ' from 00h to 09h, crc to be transmitted is 04h 42h ' The following is the demo example with 10 bytes A = 0 DATA 0,1,2,3,4,5,6,7,8,9 FOR N = 1 TO 10 READ C GOSUB CALCCRC NEXT N ' Here reordening LSB byte is transmitted first. A$ = HEX$(A) A$ = RIGHT$("0000" + A$, 4) A$ = RIGHT$(A$, 2) + LEFT$(A$, 2) PRINT "FINAL CRC: "; LEFT$(A$, 2); " "; RIGHT$(A$, 2) END ' The following is the CRC16-CCITT calculation CALCCRC: FOR V = 1 TO 8: ' 8 bits in C to process CY = (A MOD 2) + (C MOD 2): ' If = 1 carry bits different A = INT(A / 2): ' Shift Right 16 bits A C = INT(C / 2): ' Shift Right 8 bits C IF CY = 1 THEN A = A XOR 40961: ' Apply Algoritm NEXT V RETURN