C program calculates checksums

-February 15, 2001

To ensure data integrity, it's wise to frequently calculate file checksums. The C program in Listing 1 calculates the checksum of a file using a 16-bit CRC (cyclic redundancy check). The program assumes an 8-bit byte size. The routine reads the file as binary and processes one byte at a time. The CRC formula the program uses is X16+X12+X5+1, with a starting value of hexadecimal FFFF. The program displays the number of bytes processed. The file calccrc.c starts by including the header files needed. Next, the routine defines and initializes the constants. (The program does not use the C++ keyword const; therefore, a C compiler can compile the program.) Inside main(), the program defines variables and issues the initial starting value for the CRC. The routine performs a check to verify that at least two arguments passed to main(). If only one argument passes, the program terminates with a message that you need to supply a file name.

The program reads and processes one byte at a time until it reaches the end of the file. Each time the program reads a byte, the byte counter increments. At the end of the file, the program displays the CRC of the file and the number of bytes read. The routine calculates the 16-bit CRC, byte by byte, using the calcCRC16 function. This function passes the byte to be processed and the current value of the CRC and returns the new CRC value. The program calculates the CRC for each bit in the byte. The variable temp is assigned the current CRC value right-shifted 15 times, XORed with the current byte value right-shifted seven times. This operation XORs the MSB of the CRC with the MSB of the byte, so temp will have the value zero or one. Note that this operation does not change the values of the CRC or the byte. The CRC then left-shifts one place. If temp is 0, nothing happens. If temp is 1, the program XORs the CRC with hexadecimal 1021 (the X12+X5+1 term). Next, the byte left-shifts one place, so the program can process the next bit. This process repeats until the routine processes all eight bits of the byte.

If you wish to use a different formula to calculate the CRC, you need only change the variable CRC16, assuming that the formula still starts with the X16 term). If you wish to calculate a 32-bit CRC, the variables INIT and CRC16 cannot be of type int. You can set the variables SHIFT_CRC, SHIFT_BYTE, and BYTE_SIZE to other values to accommodate various byte and CRC sizes. This program is compiled using Borland C++ 3.0, Borland C++ 4.5, and Microsoft Visual C 1.0.

Loading comments...

Write a Comment

To comment please Log In