cparity

Adding a parity bit in C


I understand parity bits, but in terms of my code, I don't know how to implement it. In my class, this is the code we're working with, and I can't seem to figure out how to add the parity bit to the beginning of the binary number when it's not being stored anywhere. Each bit is just being printed as it goes.

Here's a portion of my code:

#include <stdio.h>
#define BITS 2

int main(void)
{
    int choice;
    char ch;
    int asciiChar;
    char end;
    int in;

    printf("What type of display do you want?\n");
    printf("Enter 1 for character parity, 2 for integer checksum: ");
    scanf("%d", &choice);
    if(choice == 1)
    {
        printf("Enter a character for parity calculation: ");
        scanf(" %c", &ch);

        int x = ch, i;
        int mask = 1 << sizeof(int) * BITS - 1;

        printf("x = %d\n", x);

        printf("Character: %c, ", ch);
        printf("Bit representation: ");
        for(i = 1; i <= sizeof(int) * BITS; i++)
        {
            if(x & mask)
                putchar('1');
            else
                putchar('0');
            x <<= 1;
            if(!(i % 8))
            {
                putchar(' ');
            }
        }
        printf("\n");
    }
}

What is some guidance for this?


Solution

  • Assuming the parity bit must make the byte have an even number of 1 bits: keep a count of the number of 1-bits printed and when the total is BITS-1, check if the count is odd. If yes, emit a '1', else emit a zero.

    This appends the parity bit, where normally the parity bit is prepended. If that is required, add a loop first to determine the parity bit, print it and execute your current for loop.