BIT Counting: C programming problem

Miles Bader bader+ at andrew.cmu.edu
Tue Jan 10 15:52:59 AEST 1989


jim at athsys.uucp (Jim Becker) writes:
>         The problem is the most efficient method to simply count the
> number of on bits in a sixteen bit short. This is a really easy
> exercise, but one that has a variety of different approaches. I would
> be interested in the opinions of programmers out there, an efficient
> algorithm that is understandable.

Chunk it:

#define CHUNKSIZE 8

/* table of #-bits for each index */
char numBits[1<<CHUNKSIZE]={....}; /* if big, you could init it at run-time */

int bitCount(num)
int num;
{
    int bc=0;

    while(num>0){
	bc+=numBits[num&((1<<CHUNKSIZE)-1)];
	num>>=CHUNKSIZE;
    }

    return bc;
}



More information about the Comp.lang.c mailing list