The ASCII character set uses 7 bits for storing characters. When such a character is stored in a byte, the 8 th bit (high­order) is used as a parity bit in the even­parity scheme. i.e the bit is set such that the number of 1­s in the byte are even. Write a function which accepts the character and sets the parity bit for even parity.

Source Code

Brief explanation is provided after the source code.

 
#include <stdio.h>

int isEven(int n);
void setParityBit(char);

int main(int argc, char ** argv){
    char c;
    printf("Enter a character: ");
    scanf("%c", &c);
    setParityBit(c);
    printf("\n");
    return 0;
}

void setParityBit(char c) {
    int buf[8];
    int n = c, r, i = 0, bit_counter = 0;

    while (i < 8) {

        buf[i++] = r = n%2;
        if (r == 1)
            bit_counter++;
        n = n/2;
    }

    if (isEven(bit_counter)){

    } else {
        buf[i-1] = 1;
    }

    for ( i = 7; i>=0; i--)
        printf("%d ", buf[i]);
}

int isEven(int n) {

    if(n%2 == 0)
        return 1;
    else
        return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Enter a character: d
1 1 1 0 0 1 0 0

Brief Explanation

  • The program starts by requesting the user to enter a character.
  • Using the function scanf, the character is read and assigned to the variable c. scanf reads characters from the standard input, interprets them according to the specification in format, and stores the results through the remaining arguments. scanf stops when it exhausts its format string, or when some input fails to match the control specification. int scanf(char *format, …)
  • The function setParityBit accepts the character and sets the parity bit for even parity. In the even parity system the eighth (left most) ASCII code bit can be either a zero or one. This bit is chosen so that the total number of one bits is an even number like 0,2,4,6, or 8. For example the ASCII character 'A' has hex code 41 and thus its 7 bit binary code is 1000001. Since this already has an even number (i.e. 2) of one bits, it already has even parity and so the extra eighth bit is made to be a zero so that the result: 01000001 still has an even number of one bits. As another example the ASCII character 'C' has hex code 43 and thus its 7 bit binary code is 1000011. Since this has an odd number (i.e. 3) of one bits, it is necessary to add another one bit so that the result: 11000011 will then have an even number (i.e. 4) of one bits.

Add comment


Security code
Refresh