in harry-core/src/harry/generators/RngUtils.java [145:173]
public static long randomBits(long bits, long length, LongSupplier rng)
{
long mask = bitmask(length);
if (bits == length)
return mask;
long min = 0;
long max = ~0L;
int n = 0;
int steps = 0;
while (n != bits)
{
if (steps > 10_000)
{
throw new RuntimeException(String.format("Could not generate bits after 10K tries. " +
"Inputs: bits=%d, length=%d", bits, length));
}
long x = rng.getAsLong() & mask;
x = min | (x & max);
n = Long.bitCount(x);
if (n > bits)
max = x;
else
min = x;
steps++;
}
return min;
}