Counting the number of 1-bits is relatively straightforward; you iterate over all of the bits of your number and add to some accumulator the number of bits that are set:
unsigned int X;
unsigned int count;
for (count = 0; X; X >>= 1) {
count += X & 1;
}
How it works:
- Initialize count to 0
- Start from the MSB (most significant bit) [this is the current bit]
- Add to count the result of the current bit & 1
- 1 if the bit is set
- 0 if the bit is not set
- Shift X to the right 1 bit, so the current bit is now the next MSB
- Repeat step 3
Extracting the 5th bit is also straightforward, simply right shift your number X by 5 and compute the logical AND with 1:
unsigned int fifthBit (unsigned int X) {
return (X >> 5) & 1;
}