Daniel Jour - 4 months ago 19

C Question

`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

`int`

`sizeof(int) == 4`

`INT_MIN`

`INT_MAX`

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

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

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;
srand((unsigned)time(NULL));
for (i = 0; i < 3; i++) {
rando = ((unsigned)rand() << 17) | ((unsigned)rand() << 2) | ((unsigned)rand() & 3);
printf("%u\n", rando);
}
return 0;
}
```

Program output:

```
3294784390
3748022412
4088204778
```