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; } 

Reported as a duplicate by members of Pavel Mayorov , Nick Volynkin 5 Dec '16 at 6:06 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

 int bits(unsigned int x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x>>2)&0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x += x >> 8; x += x >> 16; return x&0x3F; } int main() { for(int i = -5; i <= 5; ++i) printf("%3d %5d\n",i,bits(i)); } 
  • And there __builtin_popcount in with? And the compiler is not at hand. - pavel
  • @pavel The standard does not and should not be, as I understand it. Already very strong binding to the architecture ... - Harry
  • And such a cunning method will work if instead of an unsigned int there is just some unsigned integer type? - Parket
  • @Parket will be (possibly similar). It will be necessary to correct constants. - pavel
  • @Parket This is for 32-bit. For other types - you need to tinker a bit and redo it. But it's not that difficult ... - Harry