0

This is the code that is being written and executed and i am using gcc compiler for the same. I am using VSCode for Apple Silicon on M1 MacBook Air.

#include <stdio.h>

// Function to calculate the parity bits
void calculateParityBits(int data[], int n, int m) {
    int i, j, k;
    // Calculate the parity bits for each position that is a power of 2
    for (i = 0; i < m; i++) {
        int p = 1 << i;
        int count = 0;
        for (j = p - 1; j < n; j += 2*p) {
            for (k = 0; k < p && (j + k) < n; k++) {
                if (data[j + k] == 1) {
                    count++;
                }
            }
        }
        // Set the parity bit to 1 if the count of 1s is odd
        if (count % 2 != 0) {
            data[p - 1] = 1;
        }
    }
}

// Function to print the Hamming code
void printHammingCode(int data[], int n) {
    int i;
    for (i = 0; i < n; i++) {
        printf("%d", data[i]);
    }
}

int main() {
    // Input the data
    int data[100];
    int n, m;
    printf("Enter the length of the data: ");
    scanf("%d", &n);
    printf("Enter the number of parity bits: ");
    scanf("%d", &m);
    printf("Enter the data bits: ");
    int i;
    for (i = 0; i < n; i++) {
        scanf("%d", &data[i]);
    }
    // Calculate the parity bits
    calculateParityBits(data, n, m);
    // Print the Hamming code
    printf("Hamming code: ");
    printHammingCode(data, n + m);
    return 0;
}


The output on the terminal is as follows:

Enter the length of the data: 4  
Enter the number of parity bits: 3
Enter the data bits: 1
0
1
0
Hamming code: 1110-10634524905380585521837314128% 

The output returns garbage values. This code is working on online compilers. Please suggest appropriate fixes

I have tried resolving by using other methods to execute it but to no avail.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 1
    What output are you expecting? And have you stepped through your code with a debugger? – Stephen Newell Apr 15 '23 at 16:42
  • It might help you to output a space between each value: I get `Hamming code: 1 1 1 0 4194304 0 10`. – Weather Vane Apr 15 '23 at 17:10
  • 1
    In `calculateParityBits()`, you sometimes set elements of `data` to 1, but you never set any to 0. You need to cover both alternatives. Also, when you do set a bit, it is `data[p - 1]`, which index looks wrong. Maybe you want something more like `data[n + i] = count % 2;` (unconditionally). – John Bollinger Apr 15 '23 at 17:16
  • I was checking this: you have never written to elements 4, 5, and 6. – Weather Vane Apr 15 '23 at 17:22
  • on the point of using a debugger: https://stackoverflow.com/q/25385173/11107541 – starball Apr 16 '23 at 09:17

0 Answers0