Fletcher's Checksum - Implementation - Straightforward

Straightforward

The below is a treatment on how to calculate the checksum including the check bytes; i.e., the final result should equal 0, given properly-calculated check bytes. The code by itself, however, will not calculate the check bytes.

An inefficient but straightforward implementation of a C language function to compute the Fletcher-16 checksum of an array of 8-bit data elements follows:

  1. uint16_t Fletcher16( uint8_t* data, int count )
  2. {
  3. uint16_t sum1 = 0;
  4. uint16_t sum2 = 0;
  5. int index;
  6. for( index = 0; index < count; ++index )
  7. {
  8. sum1 = (sum1 + data) % 255;
  9. sum2 = (sum2 + sum1) % 255;
  10. }
  11. return (sum2 << 8) | sum1;
  12. }

On lines 3 and 4, the sums are 16-bit variables so that the additions on lines 9 and 10 will not overflow. The modulo operation is applied to the first sum on line 9 and to the second sum on line 10. Here, this is done after each addition, so that at the end of the while loop the sums are always reduced to 8-bits. At the end of the input data, the two sums are combined into the 16-bit Fletcher checksum value and returned by the function on line 13.

Each sum is computed modulo 255 and thus remains less than 0xFF at all times. This implementation will thus never produce the checksum results 0x00FF, 0xFF00 or 0xFFFF. It can produce the checksum result 0x0000, which may not be desirable in some circumstances (e.g. when this value has been reserved to mean "no checksum has been computed").

Read more about this topic:  Fletcher's Checksum, Implementation