In case anyone is wondering how to do an unbiased choice of the numbers 0 to N given an RNG that generates numbers 0 to 2^Y-1, where 2^Y-1 >= N, there are two ways, both rejecting some samples:
1. Find the smallest Z s.t. 2^Z-1 <= N, generate a random number, bitwise-and with 2^Z-1, accept the result if the result <= N, otherwise repeat. The expected number of times through the loop depends on Y and N, but is strictly less than 2.
2. Let W = floor((2^Z-1) / N), generate a random number, if the number < N*W, return the number mod N, otherwise repeat. The expected number of times through the loop depends on N and Y, but is no more than the first algorithm. The downside is that division and modular division are much slower than bitwise-and on most processors.
If division or modular division (on many processors, the same instruction) is much slower than bitwise-and, and your PRNG is pretty fast (such as xorshift / xorishiro), you're better off with the first algorithm.
Note that finding the mask from the first algorithm on a 64-bit machine is as simple as:
mask = N; for( i = 1; i < 64; i *= 2) { mask |= mask >> i; } // Check if your compiler unrolls this loop
Note that finding the mask from the first algorithm on a 64-bit machine is as simple as: