networking · beginner · ~15 min

XOR checksum

Compute a one-byte XOR check.

Challenge

Compute a one-byte XOR checksum (BCC) — the cheap parity check many serial protocols use.

Task

Implement unsigned char xor_checksum(const unsigned char *data, int n) that returns the XOR of all n bytes.

Input

  • data: the byte buffer.
  • n: number of bytes.

Output

The XOR of every byte, as an unsigned char.

Example

{0x01, 0x02, 0x03}  ->  0x00   (1 ^ 2 ^ 3)
{0xFF, 0x0F}        ->  0xF0

Input format

data: the byte buffer; n: the byte count.

Output format

The XOR of all n bytes, as an unsigned char.

Constraints

XOR every byte into a single-byte accumulator.

Starter code

unsigned char xor_checksum(const unsigned char *data, int n) {
    /* TODO */
    return 0;
}

Common mistakes

Forgetting 16-bit one's complement folding of carry bits; misapplying htons/ntohs; integer sign extension issues.

Edge cases to handle

Odd-length packet buffer (requiring single-byte padding); zero checksum; packets containing all 0xFF bytes.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.