Jasmine Jasmine - 1 year ago 93
C Question

Adding a parity bit in C

So 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. I hope that makes sense.

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)
x <<= 1;
if(!(i % 8))
putchar(' ');

I'm not looking for actual answers, I'm just hoping someone can provide me some guidance, thank you!

Answer Source

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.

Suggestion: as indexes in C alwas go from 0..n-1, make your loop for(i = 0; i < sizeof(int) * BITS; i++)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download