Simvik

Fix: checksums fail for some messages

Summing bytes through a plain char makes every byte above 0x7F count as negative. An easy embedded C problem (Integers and data types), run and graded in the…

easy · Integers and data types · find-the-bug · char · signedness · checksum

Bug report. The protocol's checksum is the sum of all the bytes of a message, modulo 256, as a value from 0 to 255. checksum agrees with the other end for plain text, but any message containing a byte of 0x80 or more gets a different, sometimes negative, checksum and is rejected. Fix it by changing one line.

Starter code

int checksum(const char *data, int n) {
  int sum = 0;
  for (int i = 0; i < n; i++) sum += data[i];
  return sum % 256;
}

Example tests

Text, then a binary frame

printf("%d\n", checksum("AT", 2));
const char frame[] = { 0x10, (char)0xF0, (char)0x80 };
printf("%d\n", checksum(frame, 3));

Expected output:

149
128

Learn it first

More Integers and data types problems