rand_r.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <stdlib.h>
  17. /* This algorithm is mentioned in the ISO C standard, here extended
  18. for 32 bits. */
  19. int rand_r (unsigned int *seed)
  20. {
  21. unsigned int next = *seed;
  22. int result;
  23. next *= 1103515245;
  24. next += 12345;
  25. result = (unsigned int) (next / 65536) % 2048;
  26. next *= 1103515245;
  27. next += 12345;
  28. result <<= 10;
  29. result ^= (unsigned int) (next / 65536) % 1024;
  30. next *= 1103515245;
  31. next += 12345;
  32. result <<= 10;
  33. result ^= (unsigned int) (next / 65536) % 1024;
  34. *seed = next;
  35. return result;
  36. }