Thursday, July 30, 2009

How can I count bits in a number using C code?

how to optimize code? Shall I use ASM or bit operations?

How can I count bits in a number using C code?
use bitwise operators. something like:





num_bits = 0;


for(i = 0; i %26lt; 32; i++) {


if number %26amp; (1%26lt;%26lt;i) num_bits++;


}





now num_bits holds the number of bits that were set in number. The "%26lt;%26lt;" operator does bit shifting. So "1%26lt;%26lt;i" equals a number that's all 0's except for a 1 at position i. If you bitwise and that with something, that tells you if that bit is set in the number. So we do this for each of the bits and add up the results.





This is assuming 32-bit integers. Adjust accordingly for 64-bit integers.
Reply:When I see a perfectly adequate answer destined to go unrewarded because it's the only answer, I assume the asker has "abandoned" the question. This is unfair to the answerer, so I post this "answer" to release it for voting. I would hope others do the same.


No comments:

Post a Comment