BIT Counting: C programming problem

Bernie Cosell cosell at bbn.com
Wed Jan 11 04:15:12 AEST 1989


In article <225 at tityus.UUCP> 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. 

Try this:

int BitCount(num)
    short num;
{
    int count = 0;

    while (num != 0)
	num &= num-1, count += 1;
    return (count);
}

   __
  /  )                              Bernie Cosell
 /--<  _  __  __   o _              BBN Sys & Tech, Cambridge, MA 02238
/___/_(<_/ (_/) )_(_(<_             cosell at bbn.com



More information about the Comp.lang.c mailing list