Checksum Validation

ShivdevKulshrestha
ShivdevKulshrestha

Code

#include <stdio.h>

int validate_checksum(unsigned char *mem, int n) {
    unsigned char checksum = 0;

    // XOR all bytes except the last one
    for (int i = 0; i < n - 1; i++) {
        checksum ^= *mem;
        mem++;
    }

    // Compare with the last byte (checksum)
    if (checksum == *mem) {
        return 1;
    } else {
        return 0;
    }
}

int main() {
    int n;
    scanf("%d", &n);

    unsigned char mem[100];
    for (int i = 0; i < n; i++) {
        scanf("%hhu", &mem[i]);
    }

    int result = validate_checksum(mem, n);

    printf("%d\n", result);

    return 0;
}

Solving Approach

 

 

 

Loading...

Input

5 10 20 30 40 60

Expected Output

0