The checksum function appears to be for big-endian processors only.
The first while loop is optimized for speed.
The &answer
trick loads the last byte (if there were an odd number of bytes) into the high byte of answer
, leaving the low byte zero, similar to what your code does with data[i] & 0xff00
. The way it works is this
1) take the address of answer (&answer)
2) convert that to a byte pointer (uint8_t *)
2a) on a big endian processor the first byte of a 16-bit quantity is the high byte
3) overwrite the high byte with the last byte of the data
The checksum is supposed to be computed with the carries added back in. It's assumed here that this code is running on a machine where an int
is 32-bits. Therefore, (sum & 0xffff)
is the 16-bit checksum, and (sum >> 16)
are the carry bits (if any) that need to be added back in. Hence, the line
sum = (sum >> 16) + (sum & 0xffff);
adjusts the sum to include the carries. However, that line of code could itself generate another carry bit. So the next line sum += (sum >> 16)
adds that carry (if any) back into the checksum.
Finally, take the ones-complement of the answer. Note that htons
is not used since the whole function implicitly assumes that it is running on a big endian processor.