Skip to content

Instantly share code, notes, and snippets.

@bennage
Created March 19, 2014 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennage/9654134 to your computer and use it in GitHub Desktop.
Save bennage/9654134 to your computer and use it in GitHub Desktop.
counting bits
using System;
namespace Bits
{
class Program
{
static void Main(string[] args)
{
var lookup = BuildLookup();
var input = Convert.ToUInt32("00000000000011110000100010001111", 2);
// how many bits in the input?
int count = 0;
int iterations = 0;
while (input != 0)
{
count += lookup[(byte)(input & 15)];
input = input >> 4;
iterations++;
}
Console.WriteLine("found {0} bits in {1} iterations", count, iterations);
}
private static byte[] BuildLookup()
{
const int Size = 2 << 3;
var lookup = new byte[Size];
for (int i = 0; i < Size; i++)
{
int count = 0;
int num = i;
while (num != 0)
{
count += (1 & num);
num = num >> 1;
}
lookup[i] = (byte)count;
}
return lookup;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment