How to generate a random int in C?

Is there a function to generate a random int number in C? Or will I have to use a third party library?

Solutions

Note: Don't use rand() for security. If you need a cryptographically secure number, see this answer instead.

#include <time.h>
#include <stdlib.h>

srand(time(NULL));   // Initialization, should only be called once.
int r = rand();      // Returns a pseudo-random integer between 0 and RAND_MAX.

On Linux, you might prefer to use random and srandom.

The rand() function in <stdlib.h> returns a pseudo-random integer between 0 and RAND_MAX. You can use srand(unsigned int seed) to set a seed.

It's common practice to use the % operator in conjunction with rand() to get a different range (though bear in mind that this throws off the uniformity somewhat). For example:

/* random int between 0 and 19 */
int r = rand() % 20;

If you really care about uniformity you can do something like this:

/* Returns an integer in the range [0, n).
 *
 * Uses rand(), and so is affected-by/affects the same seed.
 */
int randint(int n) {
  if ((n - 1) == RAND_MAX) {
    return rand();
  } else {
    // Supporting larger values for n would requires an even more
    // elaborate implementation that combines multiple calls to rand()
    assert (n <= RAND_MAX)

    // Chop off all of the values that would cause skew...
    int end = RAND_MAX / n; // truncate skew
    assert (end > 0);
    end *= n;

    // ... and ignore results from rand() that fall above that limit.
    // (Worst case the loop condition should succeed 50% of the time,
    // so we can expect to bail out of this loop pretty quickly.)
    int r;
    while ((r = rand()) >= end);

    return r % n;
  }
}

If you need secure random characters or integers:

As addressed in how to safely generate random numbers in various programming languages, you'll want to do one of the following:

  • Use libsodium's randombytes API
  • Re-implement what you need from libsodium's sysrandom implementation yourself, very carefully
  • More broadly, use /dev/urandom, not /dev/random. Not OpenSSL (or other userspace PRNGs).

For example:

#include "sodium.h"

int foo()
{
    char myString[32];
    uint32_t myInt;

    if (sodium_init() < 0) {
        /* panic! the library couldn't be initialized, it is not safe to use */
        return 1; 
    }


    /* myString will be an array of 32 random bytes, not null-terminated */        
    randombytes_buf(myString, 32);

    /* myInt will be a random number between 0 and 9 */
    myInt = randombytes_uniform(10);
}

randombytes_uniform() is cryptographically secure and unbiased.

Tags: C / Random

Similar questions

The difference between int(*function)(int,int) and int*function(int,int)
I am studying pointers of C and from the book of Deitel I don't get the difference between int(*function)(int,int) and int*function(int,int) when the function is expressed.
Using garbage values to generate random or Pseudo-random numbers
I come across this idea of using garbage values to generate random numbers. In C the variable that is not initialised is given a garbage value(but when I try it in my geany it gives a 0). So if want to take a random number from 50-60. Can I take the modulus of garbage values and then add them to the initial limit of the random number. But uninitial...
How to generate an integer random value within an interval, starting from random byte
I looked at the other answers I found, but they don't seem suitable to my case. I am working with ANSI C, on an embedded 32bit ARM system. I have a register that generates a random 8bit value (generated from thermal noise in the chip). From that value I would like to generate evenly distributed integer values within certain ranges, those are: 0,1,2...
Pick a random square and generate a random number
I have an board 4 x 4 (16 squares have value 0). I have to pick a random square in this board and generate a random value for this square. Here is my code Function pickSquare(int [][4]) is used to pick a random Square and generate a random value. Function printSquare(int [][4]) is used to print the board 4 x 4. I think everything is fine but when I...
How to generate random seed for random numbers
I'm trying to generate big random numbers for the public key and private key. I have problem with the initial seed to generate a random 256-bit private key on client-side. as you may know, we shouldn't use rand or srand function in C because it's easy to break. how can I generate a random seed to generate a random 256-bit private key? I use GMP's L...
write a c function that generates one random number, or a pair of random numbers, or a triplet of random numbers given the particular ranges
i have to generate random numbers for 3 different cases. i. 1 dice ii. a pair of dice iii. 3 dices my questions: 1. please suggest me sm good logic to generate random numbers for all the 3 cases. 2. does the logic change when i consider the cses of 2 dices, rather than 1? 3.how much of an effect does the range in which we have to genrate a random n...

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy.