bitqtyset

C

Public Domain

Counts the number of bits set in an int

Download (right click, save as, rename as appropriate)

Embed

Tags:

bit bits bitwise C set
1
2
3
4
5
int bitqtyset(unsigned int x) {
 int i = 0, qty = 0, j = 1;
 for (; j <= x && i < sizeof(x) * CHAR_BIT; i++, j <<= 1) if (x & j) qty++;
 return qty;
}