Example checksum calculation


An appendix gives sample C code for tagvalue message checksum calculation as:

char *GenerateCheckSum( char *buf, long bufLen )
static char tmpBuf[ 4 ];
long idx;
unsigned int cks;

for( idx = 0L, cks = 0; idx < bufLen; cks += (unsigned int)buf[ idx++ ] );
sprintf( tmpBuf, “%03d”, (unsigned int)( cks % 256 ) );
return( tmpBuf );

This example strikes me as unacceptable per modern code styles. For one thing, this code is not thread-safe.

I am asking for C experts to submit a better example to replace this one. Other language implementations are also welcome.


It would not be efficient to guarantee thread safety at this level. Thread safety would be guaranteed by the caller either by simply knowing that the message in buf is safe during this operation, or by providing the locking necessary at the message level to ensure it.

If you mean that this function could not be called in parallel then the modification I would make would simply be to have the caller pass in the buffer tmpBuf that is to be filled.

An even smarter implementation would be to write the checksum directly to the end of buf without using sprintf - something like [dusts off C syntax]

cks %= 256;
buf[bufLen+2] = '0' + cks % 10; cks /= 10;
buf[bufLen+1] = '0' + cks % 10; cks /= 10;
buf[bufLen+0] = '0' + cks;

I’ll leave it to the people more used to writing C code to provide a full implementation of this showing that buf is allocated with 3 extra chars etc. :slight_smile: