User Tools

Site Tools


mmbasic:xmodem_crc

Xmodem CRC

=== Introduction:**
This CRC (Cyclic Redundancy Check) is for the Xmodem transfer protocol. The 16 bit CRC is calculated by processing the data in a message bit by bit. It cannot correct any data corruption but can indicate if a message has been corrupted in any way.

PLEASE NOTE:

Although this is an Xmodem CRC it is in no way restricted to the Xmodem protocol. Like the Modbus CRC any message structure of any length consisting of a stream of 8-bit data bytes can utilise it to improve security. For example: Msg$ = “The quick brown fox jumps over the lazy dog”

The structure of an Xmodem message is:

Byte 1		SOH
Byte 2		Packet number (0-255)
Byte 3		Inverse packet number (255 - packet number)
Byte 4-131	128 bytes of data
Byte 132-133	16 bit CRC

The receiver responds with an ACK or NACK depending whether the CRC is good or bad. And depending on the answer the transmitter will transmit the next block of data or re-transmit the bad block. Where there are not 128 bytes of data the block of 128 is filled with a packing character. If you want to fully implement the Xmodem protocol there is plenty of infomation on the web.

Add the CRC to the message (eg: RxMsg$) by:

TxMsg$ = TxMsg$ + XCRC$(TxMsg)

and transmit it.

Performing a CRC check on a message that already includes a valid CRC will produce a 'CRC' of &h000 so: To test a recieved message (eg: RxMsg$) for a correct CRC and that it is not otherwise corrupted use:

IF XCRC$(RxMsg$) = CHR$(0) + CHR$(0) THEN ' CRC is OK
' Process the message
ELSE
' Ignore the message or send a NAK
END IF

Assumptions: None

The Function:

FUNCTION XCRC$(a$)
  LOCAL CRC% = &H0000, n%, j%
  FOR n% = 1 TO LEN(A$)
    CRC% = (CRC% AND &HFFFF) XOR (ASC(MID$(a$, n%, 1)) << 8)
    FOR j% = 1 TO 8
      IF (CRC% AND &H8000) <> 0 THEN
        CRC% = (CRC% << 1) XOR &H1021
      ELSE 
        CRC% = CRC% << 1
      END IF
    NEXT j%
  NEXT n%
  XCRC$ = CHR$(CRC% >> 8 AND &HFF) + CHR$(CRC% AND &HFF)
END FUNCTION
mmbasic/xmodem_crc.txt · Last modified: 2024/01/19 09:30 by 127.0.0.1