How can you do a 2 byte Fletchers Checksum over a range of say 4 bytes in Flowcode V5
![Question :?:](./images/smilies/icon_question.gif)
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: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.Code: Select all
uint16_t Fletcher16( uint8_t* data, int count ) { uint16_t sum1 = 0; uint16_t sum2 = 0; int index; for( index = 0; index < count; ++index ) { sum1 = (sum1 + data[index]) % 255; sum2 = (sum2 + sum1) % 255; } return (sum2 << 8) | sum1; }
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").
Code: Select all
// byte1 and byte2 are local byte variables. w is an (un)signed long (32-bit) value you wish to checksum. csum16 is an unsigned short
.byte1 = (w >> 24) + (w >> 16) + (w >> 8) + w
.byte2 = (w >> 24) + ((w >> 16) << 1) + (w >> 8) * 3 + (w << 2)
csum16 = (.byte1 & 0xFF) | (.byte2 << 8)
Code: Select all
// byte1 and byte2 are local byte variables. b is a 4-byte array you wish to checksum. csum16 is an unsigned short
.byte1 = b[3] + b[2] + b[1] + b[0]
.byte2 = b[3] + (b[2] << 1) + b[1] * 3 + (b[0] << 2)
csum16 = (.byte1 & 0xFF) | (.byte2 << 8)
No the bytes might be an array of up to 8 or more 8bit bytes.Is what you require only ever going to be from a 4 byte value?