To the StackOverflow topic I previously linked to, someone suggested the function below.
To be honest I don't understand how it works, the code comments seem to be in discordance with the code itself.
It appears to me that the code goes in Undefined Behavior territory.
/*
* Calculate a uniformly distributed random number less than upper_bound
* avoiding "modulo bias".
*
* Uniformity is achieved by generating new random numbers until the one
* returned is outside the range [0, 2**32 % upper_bound). This
* guarantees the selected random number will be inside
* [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
* after reduction modulo upper_bound.
*/
u_int32_t
arc4random_uniform(u_int32_t upper_bound)
{
u_int32_t r, min;
if (upper_bound < 2)
return 0;
/* 2**32 % x == (2**32 - x) % x */
min = -upper_bound % upper_bound;
/*
* This could theoretically loop forever but each retry has
* p > 0.5 (worst case, usually far better) of selecting a
* number inside the range we need, so it should rarely need
* to re-roll.
*/
for (;;) {
r = arc4random();
if (r >= min)
break;
}
return r % upper_bound;
}
Additionally, if the function is compiled on Pelles C, a warning about "unary -" pops up.
I've fixed that by using 0-x instead of just -x but I'm concerned I changed the meaning of the code.
Moderators: is there a way to enable syntax highlighting in code?