2OF1 · the depletionmode zineLinkedIn · X
← back to the issue

17 August 2010

Random value with limits in C

Originally published on the old depletionmode / 2of1 blog (archived copy).

There's a quick and effective way of producing a random value in C if you only require it at most once per second using current time as a random seed: #include // time_t, time() #include // srand(), rand() time_t s; time(&s); srand((unsigned int)s); // calc random value (limits are inclusive) int rand_val = 1 + (int)((float)UPPER_LIMIT * (rand() / (RAND_MAX + (float)LOWER_LIMIT))); Of course reading from /dev/urandom is good too :) (on linux).

There’s a quick and effective way of producing a random value in C if you only require it at most once per second using current time as a random seed:

listing text
#include <time.h>     // time_t, time()
#include <stdlib.h>   // srand(), rand()
 
time_t s;
time(&s);
srand((unsigned int)s);
 
// calc random value (limits are inclusive)
int rand_val = 1 + (int)((float)UPPER_LIMIT * 
               (rand() / (RAND_MAX + (float)LOWER_LIMIT)));

Of course reading from /dev/urandom is good too :) (on linux).

→ end of entry

2/1
@depletionmode
security research & systems engineering