Use the lookup table. After XORing, there are only 256 possible values, so it will not take much time. Unlike the izb solution, I would not suggest manually placing all the values, at least calculating the lookup table once at startup using one of the response loops.
For example:
public static class ByteArrayHelpers { private static readonly int[] LookupTable = Enumerable.Range(0, 256).Select(CountBits).ToArray(); private static int CountBits(int value) { int count = 0; for (int i=0; i < 8; i++) { count += (value >> i) & 1; } return count; } public static int CountBitsAfterXor(byte[] array) { int xor = 0; foreach (byte b in array) { xor ^= b; } return LookupTable[xor]; } }
(You could do this with an extension method if you really wanted to ...)
Note the use of byte[] in the CountBitsAfterXor method - you can make it IEnumerable<byte> for more generality, but iterating over the array (which is known to be an array at compile time) will be faster, probably only microscopically faster, but hey you asked for the fastest way :)
I almost certainly would have expressed it as
public static int CountBitsAfterXor(IEnumerable<byte> data)
in real life, but look what is best for you.
Also note the xor variable type as int . In fact, there is no XOR operator for byte values, and if you did xor a byte , it will still compile due to the nature of the compound assignment operators, but it will perform a throw at each iteration - at least in IL. It is possible that JIT will take care of this, but there is no need to even ask for it :)
Jon skeet
source share