K&R C Exercise 2-9 Solution

/*
 * Exercise 2-9 In a two's complement number system, 
 * x & ( x - 1 ) deletes the rightmost 1-bit in x.
 * Use this to write a fast version of bitcount.
 * 
 * Written by fduan on Dec. 14, 2011.
 */
#include <stdio.h>

/* count the number of 1 bits in x */
int bit_count( unsigned x )
{
	int n;
	for( n = 0; x != 0; x >>= 1 )
		if( x & 01 != 0 )
			++n;
	return n;
}

/* fast version of bit_count */
int fast_bit_count( unsigned x )
{
	int n = 0;
	while( x != 0 )
	{
		x &= ( x - 1 );
		++n;
	}
	return n;
}

int main()
{
	unsigned x = 100;
	printf( "%u, %u\n", bit_count( x ), fast_bit_count( x ) );
	return 0;
}

你可能感兴趣的:(K&R C Exercise 2-9 Solution)