Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use a lookup table. There are only 256 possible values after XORing, so it's not exactly going to take a long time. Unlike izb's solution though, I wouldn't suggest manually putting all the values in though - compute the lookup table <em>once</em> at startup using one of the looping answers.</p> <p>For example:</p> <pre><code>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 &lt; 8; i++) { count += (value &gt;&gt; i) &amp; 1; } return count; } public static int CountBitsAfterXor(byte[] array) { int xor = 0; foreach (byte b in array) { xor ^= b; } return LookupTable[xor]; } } </code></pre> <p>(You <em>could</em> make it an extension method if you really wanted...)</p> <p>Note the use of <code>byte[]</code> in the <code>CountBitsAfterXor</code> method - you <em>could</em> make it an <code>IEnumerable&lt;byte&gt;</code> for more generality, but iterating over an array (which is known to be an array at compile-time) will be faster. Probably only microscopically faster, but hey, you asked for the <em>fastest</em> way :)</p> <p>I would almost certainly <em>actually</em> express it as</p> <pre><code>public static int CountBitsAfterXor(IEnumerable&lt;byte&gt; data) </code></pre> <p>in real life, but see which works better for you.</p> <p>Also note the type of the <code>xor</code> variable as an <code>int</code>. In fact, there's no XOR operator defined for <code>byte</code> values, and if you made <code>xor</code> a <code>byte</code> it would still compile due to the nature of compound assignment operators, but it would be performing a cast on each iteration - at least in the IL. It's quite possible that the JIT would take care of this, but there's no need to even ask it to :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload