Daniel Jour Daniel Jour - 10 months ago 38
C Question

How to generate a random number from whole range of int in C?

unsigned const number = minimum + (rand() % (maximum - minimum + 1))

I know how to (easily) generate a random number within a range such as from 0 to 100. But what about a random number from the full range of
sizeof(int) == 4
), that is from
, both inclusive?

I don't need this for cryptography or the like, but a approximately uniform distribution would be nice, and I need a lot of those numbers.

The approach I'm currently using is to generate 4 random numbers in the range from 0 to 255 (inclusive) and do some messy casting and bit manipulations. I wonder whether there's a better way.

Answer Source

On my system RAND_MAX is 32767 which is 15 bits. So for a 32-bit unsigned just call three times and shift, or, mask etc.

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

int main(void){
    unsigned rando, i;
    for (i = 0; i < 3; i++) {
        rando = ((unsigned)rand() << 17) | ((unsigned)rand() << 2) | ((unsigned)rand() & 3);
        printf("%u\n", rando);
    return 0;

Program output: