title: Generate a random binary number with a variable proportion of '1' bits
body: <p>I need a function to generate random integers. (assume Java <code>long</code> type for now, but this will be extended to <code>BigInteger</code> or <code>BitSet</code> later.)</p>
  
  <p>The tricky part is there is a parameter P that specifies the (independent) probability of any bit in the result being 1.</p>
  
  <p>If P = 0.5 then we can just use the standard random number generator.  Some other values of P are also easy to implement.  Here's an incomplete example:</p>
  
  <pre><code>Random random = new Random();
  
  // ...
  
  long nextLong(float p) {
      if      (p == 0.0f)   return 0L;
      else if (p == 1.0f)   return -1L;
      else if (p == 0.5f)   return random.nextLong();
      else if (p == 0.25f)  return nextLong(0.5f) &amp; nextLong(0.5f);
      else if (p == 0.75f)  return nextLong(0.5f) | nextLong(0.5f);
      else if (p == 0.375f) return nextLong(0.5f) &amp; nextLong(0.75f); // etc
      else {
        // What goes here??
        String message = String.format("P=%f not implemented yet!", p);
        throw new IllegalArgumentException(message);
      }
  }
  </code></pre>
  
  <p>Is there a way to generalise this for any value of P between 0.0 and 1.0?</p>