47. Checksum Validation

#include <stdio.h>

int validate_checksum(int *mem, int n) {
    int *ptr = mem;
    int xor_result = 0;

    for (int i = 0; i < n - 1; i++) {
        xor_result ^= *ptr;
        ptr++;
    }

    int checksum = *ptr;  // last byte is the checksum
    return xor_result == checksum ? 1 : 0;
}

int main() {
    int n, arr[100];
    scanf("%d", &n);
    
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int result = validate_checksum(arr, n);
    printf("%d", result);

    return 0;
}

Checksums are lightweight data validation methods used in firmware protocols (UART, I2C, Modbus) to detect transmission errors.

XOR checksum is very common in small data transfers.

Solution Logic:

  • Loop over first n-1 bytes using a pointer
  • XOR each value into a xor_result
  • Compare the result with the last byte (checksum)
  • Return 1 if valid, else 0
     
Loading...

Input

5 10 20 30 40 60

Expected Output

0