Receive bytes from / dev / urandom within a range while keeping a fair distribution

I want to generate random numbers in an assembly (nasm, linux) and I don't want to use libc (for didactic reasons), so I plan to read / dev / urandom.

The point is, I would like them to be in a certain range.

For example, let's say I want a number between 0 and 99.

When I read a byte from / dev / urandom it will be in the range 0x00 to 0xff (255).

One thing I could do is apply mod 100, which would guarantee the correct range.

But the problem with this approach is that some numbers are more likely to come out than others.

The number 51 came out of 3 different results:

51  % 100 = 51
151 % 100 = 51
251 % 100 = 51


The number 99 came from only two different results:

99  % 100 = 99
199 % 100 = 99
(there will be no 299 since the range of a byte ends in 255).


The only solution I have come up with is to drop the random number when it is in the 200-255 range and read another.

Is there a smarter way to read a random byte and make sure it is in a certain range while being "fair"?

What if I plan to read many bytes within the range? Is there a way to be fair without giving up many of Uram's readings?

I have heard of the getrandom (2) linux system call, but it is not in stable kernel yet (3.16.3 from now). Is there any alternative?


source to share

All Articles