Compute parity bit

© Parineeth M R

Question 34. Given an integer, compute the parity bit for the integer


There are two types of parity bit schemes

1. Even parity: if the total number of 1’s is odd, then the parity bit will be 1 to make the total number of 1’s (including the parity bit) even

2. Odd parity: if the total number of 1’s is even, then the parity bit will be 1 to make the total number of 1’s (including the parity bit) odd.

We will implement an even parity scheme here. We count the number of 1’s in the integer using the scheme described in problem 29

C/C++


/*
x: input integer
Return value: parity bit, 1 if there are odd number of 1's, 0 otherwise
*/
unsigned int compute_parity(unsigned int x) 
{
	/*for each bit set to 1 in x, toggle the parity bit*/
	unsigned int parity = 0;
	while (x != 0) {
		parity = parity ^ 1;
		x = x & (x - 1);
	}

	return parity;
}



Java


/*
x: input integer
Return value: parity bit, 1 if there are odd number of 1's, 0 otherwise
*/
public static int computeParity( int x) {
	/*for each bit set to 1 in x, toggle the parity bit*/
	int parity = 0;
	while (x != 0) {
		parity = parity ^ 1;
		x = x & (x - 1);
	}

	return parity;
}



Python


#x: input integer
#Return value: parity bit, 1 if there are odd number of 1's, 0 otherwise
def compute_parity(x):
	#for each bit set to 1 in x, toggle the parity bit
	parity = 0
	while (x):
		parity = parity ^ 1
		x = x & (x - 1)

	return parity