0

Working with a program in c that reads in a file and then I have to do both 8 bit and 16 bit checksum for a program.I only have 8 bit checksum done so far.

This is what I understand

I read the file and store the information in an array of characters and at end it takes the newline feed. so for example to calculate 8 bit check sum this is what happens essentially

File has 3 letters total ( 3 a's and a newline feed)

so array holds 4 chars aaa+(newline) (97+97+97+10)

To my understanding I add all the bytes in the array then do % 256 and that is my checksum.

97 * 3 = //3 a's (small a ) pulled from ascii table from what I understand

291 + 10 = 301 // + newline

301 % 256 = cc in hex //

however I am getting confused on how to calculate the 16 bit checksum because I can't add 2 characters at a time if its a single character array?

any help would be greatly appreciated

Barmar
  • 741,623
  • 53
  • 500
  • 612
Los
  • 11
  • 1
  • 1
  • 1
  • 1
    I hate to answer a question with a question, but why 256? What is significant about that number and how would it be different when checking 16 bits? Also, 301 is a number that doesn't fit into a single byte. That got me thinking about [unsigned overflow and modulo operations](https://stackoverflow.com/questions/21611184/is-arithmetic-overflow-equivalent-to-modulo-operation). – James Poag Oct 25 '18 at 01:26
  • Is this a simple check sum algorithm, or any other modification? This is not clear from the description. For simple check sum just use `sum & 0xffff` or `(unsigned short)sum` *(where the `unsigned short` represents 16 bit unsigned integer)*, or `sum % 65536`, if you like *(but I do not recommend this last option; not that there will be a different result, but I think it is better to use `&` or retyping for better readability)*. And of course, use sum only when this is a homework; for serious use [select another hash algorithm](https://en.wikipedia.org/wiki/List_of_hash_functions). – Julo Oct 25 '18 at 01:37
  • I recently found [Tutorial: Checksum and CRC Data Integrity Techniques for Aviation](https://users.ece.cmu.edu/~koopman/pubs/KoopmanCRCWebinar9May2012.pdf), but that probably is more than you want to know on the topic... – U. Windl Jan 27 '23 at 11:22

1 Answers1

2

To calculate a 16-bit checksum, you process the array in increments of 2, and put one byte into the low-order byte of the value that you're adding, and the other byte into the high-order byte.

uint8_t array[MAX]; // The data gets copied into here
size_t length; // This is the length of the data
uint16_t checksum = 0;
size_t even_length = length - length%2; // Round down to multiple of 2
for (int i = 0; i < even_length; i += 2) {
    uint16_t val = array[i] + 256 * array[i+1];
    checksum += val;
}
if (i < length) { // Last byte if it's odd length
    checksum += array[i];
}

There's no need to use modulus, since unsigned integers implement modular arithmetic automatically.

Barmar
  • 741,623
  • 53
  • 500
  • 612