librfn
An ad-hoc utility library
rand.c
Go to the documentation of this file.
1 /*
2  * rand.c
3  *
4  * Part of librfn (a general utility library from redfelineninja.org.uk)
5  *
6  * Copyright (C) 2012 Daniel Thompson <daniel@redfelineninja.org.uk>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published
10  * by the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  */
13 
14 #include "librfn/rand.h"
15 
16 #include <stdint.h>
17 
18 /* Derived from code placed in the public domain by Robin Whittle
19  *
20  * 3rd generated number (starting from a seed of 1) should be 1622650073,
21  * 10th is 2007237709, and 10000th is 1043618065.
22  */
23 uint32_t rand31_r(uint32_t *seedp)
24 {
25  uint32_t hi, lo;
26 
27  lo = 16807 * (*seedp & 0xffff);
28  hi = 16807 * (*seedp >> 16);
29 
30  lo += (hi & 0x7fff) << 16;
31  lo += hi >> 15;
32 
33  if (lo > 0x7fffffff)
34  lo -= 0x7fffffff;
35 
36  return (*seedp = lo);
37 }
38 
uint32_t rand31_r(uint32_t *seedp)
Definition: rand.c:23