[OCLUG-devel] Limiting range of random numbers

James Colannino james at colannino.org
Fri Nov 19 17:51:48 PST 2004


Hey everyone,

I'm using the following code snippet to generate suedo-random numbers:

#include <stdio.h>
#include <stdlib.h>

int random() {


    char seed;   /* random number seed */


    /* open /dev/urandom for binary read-only */

    FILE *filename;
    filename = fopen ("/dev/urandom", "rb");


    fread (&seed, 1, 1, filename);
        /* read 1 byte from /dev/urandom into seed */


    fclose (filename);


    srand (seed);   /* seeds rand() */
    int random_number = rand();


    return number;
}

It works great for me.  The only problem is, all the numbers I get are 
quite large, something like 19348382 (as an example.)  I'd like to 
restrict the possible numbers to a given range, perhaps from 0 to 10 or 
some much smaller number like that.  How would I go about this?  Thanks 
in advance.

James


More information about the OCLUG-devel mailing list