Cyclical Redundancy Check (CRC)
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.
- Set CRC to 0.
- Get next byte from data stream.
-
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.
- Shift the input byte left 1.
- If you have not shifted the input byte 8 times go to step 3.
- If you have remaining bytes in the data stream go to step 2.
A theoretical explanation of this algorithm can be found in Numerical
Recipes in C:The Art of Scientific Computing.1
A C function that calculates the CRC one bit at a time follows:
rt 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;
}