title: Most efficient method of generating a random number with a fixed number of bits set
body: <p>I need to generate a random number, but it needs to be selected from the set of binary numbers with equal numbers of set bits. E.g. choose a random byte value with exactly 2 bits set...</p>
  
  <pre><code>00000000 - no
  00000001 - no
  00000010 - no
  00000011 - YES
  00000100 - no
  00000101 - YES
  00000110 - YES
  ...
  
  =&gt; Set of possible numbers 3, 5, 6...
  </code></pre>
  
  <p>Note that this is a simplified set of numbers. Think more along the lines of 'Choose a random 64-bit number with exactly 40 bits set'. Each number from the set must be equally likely to arise.</p>