_If_ memory is not a huge problem then declare an array of 256 numbers [to be indexed by an 8 bit index]. ith element will contain number of bits set in the number i.

assume int is 4 bytes.

num_bit_set = arr[x & 0xFF] + arr [(x>>

& 0xFF] + arr [x>>16 & 0xFF] + arr [x>>24 & 0xFF]

-----

a small test can be added. If the number is a power of 2 then this is not needed answer will be 1. The logic to check whether a number is power of 2 or not is:

(x != 0) && !(x & (x - 1)

------

If there are other solutions using bit masking hacks please share