Checksum encoder

#include <stdio.h>

int main() {
    int a[10], b[10], sum[10], chk[10], carry = 0, n, i;

    printf("Checksum Program for Two Segments\n");
    printf("Enter the number of bits in each segment: ");
    scanf("%d", &n);

    // Input the two segments
    printf("Enter the first segment (%d bits): ", n);
    for (i = n - 1; i >= 0; i--) {
        scanf("%d", &a[i]);
    }

    printf("Enter the second segment (%d bits): ", n);
    for (i = n - 1; i >= 0; i--) {
        scanf("%d", &b[i]);
    }

    // Calculate the sum of the two segments with carry
    for (i = 0; i < n; i++) {
        sum[i] = (a[i] + b[i] + carry) % 2;
        carry = (a[i] + b[i] + carry) / 2;
    }

    // Add carry to the sum if it exists
    if (carry == 1) {
        for (i = 0; i < n; i++) {
            int temp = (sum[i] + carry) % 2;
            carry = (sum[i] + carry) / 2;
            sum[i] = temp;
        }
    }

    // Calculate the checksum (1's complement of the sum)
    printf("Checksum: ");
    for (i = n - 1; i >= 0; i--) {
        chk[i] = sum[i] == 1 ? 0 : 1; // Invert the bits
        printf("%d", chk[i]);
    }
    printf("\n");

    return 0;
}

Comments