G
G Patel
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? */
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? */