1

If i have 2 binary number representation: 127 and 128. How can i calculate that 127 have 7 bits "ON" and 128 have only 1 bit "ON"?

I did it like the following, but i think there's probably a better way (with math):

strlen(str_replace('0','',decbin(127))); // 7
strlen(str_replace('0','',decbin(128))); // 1

1 Answers1

0

It looks like what you want is a population count. The Wikipedia reference has some code, and for problems like this I always check Bit Twiddling Hacks which is a great reference.

There are asm instructions for this on some machines, and both gcc and MSVC have compiler builtins.

For other languages, see: Population Count on RosettaCode

DanaJ
  • 724
  • 6
  • 9
  • it seems my method is much easier... I thought there would be a very simple mathematical method to solve it. Thank you! – Learning_to_program Aug 26 '14 at 14:44
  • I see, something like testing for powers of two via "!(n&(n-1))". In C most people are concerned with the speed rather than the number of source characters, but it's easier in some languages (e.g. Python: bin(n).count("1")) – DanaJ Aug 26 '14 at 14:49