BSD checksum
From Wikipedia, the free encyclopedia
Below is the relevant part of the GNU sum source code (GPL licensed). It computes a 16-bit checksum by adding up all bytes (8-bit words) of the input data stream. In order to avoid many of the weaknesses of simply adding the data, the checksum accumulator is circular rotated to the right by one bit at each step before the new char is added.
int bsdChecksumFromFile(FILE *fp) /* The file handle for input data */
{
int checksum = 0; /* The checksum mod 2^16. */
for (int ch = getc(fp); ch != EOF; ch = getc(fp)) {
checksum = (checksum >> 1) + ((checksum & 1) << 15);
checksum += ch;
checksum &= 0xffff; /* Keep it within bounds. */
}
return checksum;
}