Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • 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);

.Net Core 3.0 or newer required
#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