Created
March 19, 2014 23:46
-
-
Save bennage/9654134 to your computer and use it in GitHub Desktop.
counting bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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