function to count number of set bits

From: G Patel (gaya.patel_at_gmail.com)
Date: 01/29/05


Date: 29 Jan 2005 14:06:16 -0800

Hi, I'm wondering if anyone knows if the following function will
function properly as a set-bit counter on non 2s complement machines
(as K&R2 implies).

| int bitcount(unsigned x)
| {
| int count;
|
| for(count = 0; x != 0; count++, x &= (x-1))
| ;
|
| return count;
| }

I can't think of a reason why this would fail on a 1s complement or
sign-mag machine (and can't find a non 2s compliment machine to try it
on). Is it portable as far as C is concerned?

And also, if I declare a signed int in the main program and want to set
the msb to 1, can I do this (32bit ints)?:

int b = 0x8000000;
/* is the 0x80000000 taken as an unsigned long constant or a signed
int? */

int count = bitcount(b);
/* is this undefined- trying to send a negative int to bitcount
function? */



Relevant Pages

  • Re: function to count number of set bits
    ... > function properly as a set-bit counter on non 2s complement machines ... rightmost set bit on all implementations - negative 'even' integers in ... > | int bitcount ...
    (comp.lang.c)
  • Re: checking array indices
    ... there is no negative value of type int that yields a value less ... >> representations where this isn't the case.) ... > zero machine cycles on two's complement machines. ... In an assert, this is ...
    (comp.lang.c)
  • Re: >>> ??
    ... > int inthash ... Is it Java or C# code, ... vacant bits to the left are filled with a copy ... two's complement machines. ...
    (microsoft.public.vc.language)
  • Re: function to count number of set bits
    ... > function properly as a set-bit counter on non 2s complement machines ... > | int bitcount ... implementations, `b' will be initialized to INT_MIN, -2147483648 -- ... representation of -1 on a signed magnitude machine has two ...
    (comp.lang.c)
  • Re: Help me understand this compiler warning.
    ... signed int, since a signed int can hold all the values of an unsigned ... This is called a "value preserving" promotion. ... If the pre-standard C compiler for the AT&T implementation used the ...
    (comp.lang.c)