Counting bits set in a .Net BitArray Class

This is my solution based on the “best bit counting method” from http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel public static Int32 GetCardinality(BitArray bitArray) { Int32[] ints = new Int32[(bitArray.Count >> 5) + 1]; bitArray.CopyTo(ints, 0); Int32 count = 0; // fix for not truncated bits in last integer that may have been set to true with SetAll() ints[ints.Length – 1] … Read more

BitArray – Shift bits

This simple snippet shows a manual way to do it. The value of bitArray[0] is overwritten: //… bitArray is the BitArray instance for (int i = 1; i < bitArray.Count; i++) { bitArray[i – 1] = bitArray[i]; } bitArray[bitArray.Count – 1] = false // or true, whatever you want to shift in Making this an … Read more

C/C++ Bit Array or Bit Vector

I think you’ve got yourself confused between arrays and numbers, specifically what it means to manipulate binary numbers. I’ll go about this by example. Say you have a number of error messages and you want to return them in a return value from a function. Now, you might label your errors 1,2,3,4… which makes sense … Read more

Is BitArray faster in C# for getting a bit value than a simple conjuction with bitwise shift?

@Jonathon Reinhart, your benchmark is unfortunately inconclusive. It does not take into account the effects of possible lazy-loading, caching and/or prefetching (by the CPU, the host OS and/or the .NET runtime). Shuffle the order of the tests (or call the test methods multiple times) and you might notice different time measurments. I did your original … Read more