This question has already been answered:
I need to count the number of units in a binary number. With the positive numbers I figured out, but it is not clear how to implement the algorithm with negative ones. Negative numbers are represented in an additional code.
int bitcount(int n) { unsigned int c1 = 0; for (; n > 0; n >>= 1) if (n & 1) { c1++; } return c1; } int main() { int a = -2; printf("%u \n", bitcount(a)); return 0; }
unsigned, and go ... - Harry