Guest User

mkrnd.c

a guest
Dec 26th, 2015
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. /*
  2. * mkrnd - generate random number
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <stdint.h>
  9. #include <string.h>
  10. #include <sys/time.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. #include <fcntl.h>
  14.  
  15. static uint32_t randrange(uint32_t s, uint32_t d)
  16. {
  17. uint32_t c;
  18. int f = -1;
  19. struct timeval t; memset(&t, 0, sizeof t);
  20.  
  21. if (d < s) return s;
  22.  
  23. #if 0
  24. f = open("/dev/urandom", O_RDONLY);
  25. if (f == -1) f = open("/dev/random", O_RDONLY);
  26. if (f == -1) goto _rand;
  27. read(f, &c, sizeof(uint32_t));
  28. close(f);
  29. goto _norand;
  30.  
  31. _rand:
  32. #endif
  33. gettimeofday(&t, NULL);
  34. c ^= (((t.tv_sec * t.tv_usec) * t.tv_sec) << 15) ^ t.tv_usec;
  35. srandom(c);
  36. c = random();
  37. #if 0
  38. _norand:
  39. #endif
  40. c = c % (d - s + 1 == 0 ? d - s : d - s + 1) + s;
  41.  
  42. return c;
  43. }
  44.  
  45. static uint64_t randrangel(uint64_t s, uint64_t d)
  46. {
  47. uint64_t c;
  48.  
  49. c = randrange(0, (uint32_t)0xffffffff);
  50. c <<= 32;
  51. c |= randrange(0, (uint32_t)0xffffffff);
  52.  
  53. c = c % (d - s + 1 == 0 ? d - s : d - s + 1) + s;
  54.  
  55. return c;
  56. }
  57.  
  58. int main(int argc, char **argv)
  59. {
  60. uint64_t x;
  61.  
  62. if (argc < 4) return 1;
  63.  
  64. for (x = 0; x < atoll(*(argv+3)); x++)
  65. printf("%lld\n", randrangel(atoll(*(argv+1)), atoll(*(argv+2))));
  66.  
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment