# Native Mode Checksum

The checksum that is used by Native Mode file transfer commands is a standard 16-bit Cyclical Redundancy Check (CRC). The algorithm for calculating the CRC follows. In this example the variable CRC is unsigned 16 bits and the input byte is 8 bits.

1. Set CRC to 0.
2. Get next byte from data stream.

3. Test the most significant bit of CRC and the input byte and do the following:

   If they are equal shift CRC left 1.

   If one bit is 0 and the other 1 then shift CRC left 1 and XOR with 4129.

4. Shift the input byte left 1.
5. If you have not shifted the input byte 8 times go to step 3.
6. If you have remaining bytes in the data stream go to step 2.

You can find a theoretical explanation of this algorithm in Numerical Recipes in C:The Art of Scientific Computing.1 Press, William H., et al. Cambridge, MA: Cambridge University Press, 1992, 896-901.
A C function that calculates the CRC one bit at a time follows:

    unsigned short CalculateCRC(char* buffer, int size)
    {
      unsigned short cword = 0;
      unsigned short ch;
      int i,j;
      for (i = 0; i < size; i++) {
        ch = buffer[i] << 8;
        for (j = 0; j < 8; j++) {
          if ((ch & 0x8000) ^ (cword & 0x8000)) {
            cword = (cword << 1) ^ 4129;
          }
          else {
            cword <<= 1;
          }
          ch <<= 1;
        }
      }
      return cword;
    }

The vision system calculates the checksum of a transferred file from the ASCII character values of the hexadecimal encoded file contents. For example:

File Contents | 0xAB 0xCD 0xEF 0x01
ASCII Representation | ABCDEF01
Byte Values to Check | 0x41 0x42 0x43 0x44 0x45 0x46 0x30 0x31

This encoding for file transfers over Native Mode commands adds a sequence of a carriage return and a line feed character after every 80 visible characters.