rand_r.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* Reentrant random function frm POSIX.1c.
  2. Copyright (C) 1996, 1999 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Ulrich Drepper <drepper@cygnus.com <mailto:drepper@cygnus.com>>, 1996.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, write to the Free
  15. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 USA. */
  17. #include <stdlib.h>
  18. /* This algorithm is mentioned in the ISO C standard, here extended
  19. for 32 bits. */
  20. int rand_r (unsigned int *seed)
  21. {
  22. unsigned int next = *seed;
  23. int result;
  24. next *= 1103515245;
  25. next += 12345;
  26. result = (unsigned int) (next / 65536) % 2048;
  27. next *= 1103515245;
  28. next += 12345;
  29. result <<= 10;
  30. result ^= (unsigned int) (next / 65536) % 1024;
  31. next *= 1103515245;
  32. next += 12345;
  33. result <<= 10;
  34. result ^= (unsigned int) (next / 65536) % 1024;
  35. *seed = next;
  36. return result;
  37. }