yogur yogur - 4 months ago 33
C++ Question

How can I use Linux getrandom system call to generate a random number within a range?

I have the following piece of code

#include <unistd.h>
#include <sys/syscall.h>
#include <linux/random.h>

unsigned long int s;
syscall(SYS_getrandom, &s, sizeof(unsigned long int), 1);
std::cout << s << std::endl;

According to GETRANDOM(2) it returns random numbers from /dev/random or /dev/urandom with high entropy.

How can I use it to return numbers within a range? The range I'm using is [0 - 2^125] [0 - 125^2]


Assuming that whatever SYS_getrandom uses is a true generator (rather than a pseudorandom one), your best bet in this instance is to recognise that 125 * 125 is very close to the 14th power of 2, and go from there.

So pass a 16 bit unsigned as the buffer, read in 14 bits from the generator, and perform any necessary bitwise operations on the result. This will give you a number in the range 0 to 16383 inclusive.

Resample if the number is outside the desired range: a probability of about 5%.

With a pseudo random number generator, resampling can introduce statistical anomalies (higher moments than the mean go off), but with a true generator it doesn't.