Logo

Programming-Idioms

Count number c of 1s in the integer i in base 2.

E.g. i=6 → c=2
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#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);
(def c (count (re-seq #"1" (Integer/toBinaryString i))))
#include <cstdint>
uint32_t c = 0;
for (; i; i &= i - 1, ++c);
public static int BitCount(int i)
{
    var c = 0;
    while (n != 0)
    {
        c++;
        n &= (n - 1); //walking through all the bits which are set to one
    }

    return c;
}
using System.Numerics;
var c = BitOperations.PopCount((uint)i);
import std.bitmanip;
auto c = bitSet(i).length;
var c = i.toRadixString(2).replaceAll('0','').length;
c = popcnt(i)
import "math/bits"
c := bits.OnesCount(i)
func PopCountUInt64(i uint64) (c int) {
	i -= (i >> 1) & 0x5555555555555555
	i = (i>>2)&0x3333333333333333 + i&0x3333333333333333
	i += i >> 4
	i &= 0x0f0f0f0f0f0f0f0f
	i *= 0x0101010101010101
	return int(i >> 56)
}

func PopCountUInt32(i uint32) (n int) {
	i -= (i >> 1) & 0x55555555
	i = (i>>2)&0x33333333 + i&0x33333333
	i += i >> 4
	i &= 0x0f0f0f0f
	i *= 0x01010101
	return int(i >> 24)
}
c = Data.Bits.popCount i
const c = i.toString(2).replace(/[^1]/g, '').length
import static java.lang.String.valueOf;
import java.math.BigInteger;
int c = new BigInteger(valueOf(i), 2).bitCount();
int c = Integer.bitCount(i);
(setf c (logcount i))
$i = base_convert($i,10,2);
$x = str_replace(0,'',$i);
$c = strlen($x);
function BitCount(N: Int64): Integer;
var
  Q: QWord;
  i: Integer;
begin
  Result := 0;
  Q := QWord(N);
  for i := 0 to (8 * SizeOf(N) - 1) do
  begin
    if ((Q and 1) = 1) then Inc(Result);
    Q := Q shr 1;
  end;
end;
c := PopCnt(i);
# Not best, but simple:
$c=0;
while ($i) {
   $c += $i&1;
   $i /= 2;
}
$c = unpack '%b*', pack 'i', $i;
c = bin(i).count("1")
c = i.bit_count()
c = i.digits(2).count(1)
let c = i.count_ones();