stdlib: force rand() to return a non-negative number

Negative numbers come with tricky modulus results and are excluded from
the return values of the standard rand().
This commit is contained in:
Lephe 2020-10-09 09:17:48 +02:00
parent 078edb50b2
commit 52d95e72ed
No known key found for this signature in database
GPG key ID: 1BBA026E13FC0495
2 changed files with 4 additions and 2 deletions

View file

@ -19,10 +19,12 @@ void *calloc(size_t nmemb, size_t size);
/* realloc(): Reallocate dynamic memory */ /* realloc(): Reallocate dynamic memory */
void *realloc(void *ptr, size_t size); void *realloc(void *ptr, size_t size);
#define RAND_MAX 0x7fffffff
/* srand(): Seed the PRNG */ /* srand(): Seed the PRNG */
void srand(unsigned int seed); void srand(unsigned int seed);
/* rand(): Generate a pseudo-random number */ /* rand(): Generate a pseudo-random number between 0 and RAND_MAX */
int rand(void); int rand(void);
#endif /* GINT_STD_STDLIB */ #endif /* GINT_STD_STDLIB */

View file

@ -10,5 +10,5 @@ void srand(unsigned int seed)
int rand(void) int rand(void)
{ {
return tinymt32_generate_uint32(&random); return tinymt32_generate_uint32(&random) & 0x7fffffff;
} }