Reference

Checksums

 

 

Checksums provide a simple way of detecting and rejecting data corruption or transmission errors.

 

Checksum Algorithms

A checksum works by adding up the individual bits or bytes of a message, and appending the resultant value to the packet that is sent.  The receiving device (or computer) performs the same calculation on the message data, and compares the calculated result to the checksum in the packet.  If the two values are equal, that means that the message is "ok".

 

Checksum values are not typically used in Ethernet-based device protocols, because the low-level TCP/IP and UDP/IP parts of Ethernet automatically include checksums and other error-correction of their own.

 

Basic Checksum

The simplest type of checksum is to add together all the byte values in a message, and use the least-significant byte of the sum as the checksum byte.

 

For example, consider the following byte values:

 

 

0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64, 0x2E

 

 

The sum of these byte values is 0x046A.  The checksum byte is the least-significant byte of the sum, which is 0x6A (i.e. the rightmost two hex digits).

 

 

72 + 101 + 108 + 108 + 111 + 32 + 119 + 111 + 114 + 108 + 100 + 46 = 1130 = 0x046A

 

 

A simple checksum like this has a few limitations:

 

For most purposes, however, a basic checksum algorithm such as this is usually adequate.  Your device protocol should document the exact checksum algorithm it uses.

 

Design Pattern

The Calculate Checksum pattern shows how to implement a basic checksum:

 

 

byte[] data = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64, 0x2E };

byte checksum = CalculateChecksum( data );

 

 

the resultant checksum value will be 0x6A.  The calculated checksum byte can then be appended to the outgoing packet for sending data, or compared with the received checksum for incoming data.

 

For full a tutorial you can follow the Modifying_and_Extending_Drivers sample.

 

Advanced Checksums

There are numerous algorithms for calculating complex checksums, error recovery information, data signatures and hashes that are well beyond the scope of this topic.  A few common algorithms that may be used in some advanced serial protocols are CRC32 and MD5.

 

See Also

Write my Own Driver

Design Patterns Index