wrote:
>
> count the bits required to be altered while swaping values a and b
/* BEGIN new.c */
#include <stdio.h>
#include <stdlib.h>
unsigned bit_count(unsigned n);
int main(void)
{
unsigned a, b, mask;
a = rand();
b = rand();
mask = a ^ b;
printf("a is %u\nb is %u.\n", a, b);
printf("%u bits would need to be flipped in each object\n"
"to swap their values.\n", bit_count(mask));
printf("%u ^ %u is %u\n", a, mask, a ^ mask);
printf("%u ^ %u is %u\n", b, mask, b ^ mask);
return 0;
}
unsigned bit_count(unsigned n)
{
unsigned count;
for (count = 0; n != 0; n &= n - 1) {
++count;
}
return count;
}
/* END new.c */
--
pete