Logo

Programming-Idioms

  • Python
  • Ruby
  • JS
  • Java
  • Scala
  • Clojure
(def c (count (re-seq #"1" (Integer/toBinaryString i))))
c = i.bit_count()

For Python 3.10+
c = bin(i).count("1")
c = i.digits(2).count(1)
const c = i.toString(2).replace(/[^1]/g, '').length

• Convert the number to binary
• Replace characters that aren't '1' by turning them to ''
• See how long the resulting list of '1's is
import static java.lang.String.valueOf;
import java.math.BigInteger;
int c = new BigInteger(valueOf(i), 2).bitCount();
int c = Integer.bitCount(i);

i has type int.

Warning: small negative numbers have a lot of bits set, because of the two's complement.

Similar methods exist in classes Long and BigInteger.
#include <stdint.h>
uint32_t c = i;
c = (c & 0x55555555) + ((c & 0xAAAAAAAA) >> 1);
c = (c & 0x33333333) + ((c & 0xCCCCCCCC) >> 2);
c = (c & 0x0F0F0F0F) + ((c & 0xF0F0F0F0) >> 4);
c = (c & 0x00FF00FF) + ((c & 0xFF00FF00) >> 8);
c = (c & 0x0000FFFF) + ((c & 0xFFFF0000) >> 16);

add even and odd bits
then add even and odd pairs of bits
then add even and odd quadruples of bits
then add even and odd octets of bits
then add whatever groups of 16 bits are called
done

with gcc you can also use the function _builtin_popcount

New implementation...
< >
deleplace