Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
rand.c File Reference
#include <stdlib.h>
Include dependency graph for rand.c:

Go to the source code of this file.

Functions

static int do_rand (unsigned long *ctx)
 
 __attribute__ ((weak))
 

Variables

static unsigned long next = 1
 

Function Documentation

◆ __attribute__()

__attribute__ ( (weak)  )

Definition at line 71 of file rand.c.

72 {
73  unsigned long val = (unsigned long)*ctx;
74  int r = do_rand(&val);
75 
76  *ctx = (unsigned int)val;
77  return (r);
78 }
static int do_rand(unsigned long *ctx)
Definition: rand.c:35

References do_rand().

◆ do_rand()

static int do_rand ( unsigned long *  ctx)
static

Definition at line 35 of file rand.c.

36 {
37 #ifdef USE_WEAK_SEEDING
38  /*
39  * Historic implementation compatibility.
40  * The random sequences do not vary much with the seed,
41  * even with overflowing.
42  */
43  return ((*ctx = *ctx * 1103515245 + 12345) % ((unsigned long)RAND_MAX + 1));
44 #else /* !USE_WEAK_SEEDING */
45  /*
46  * Compute x = (7^5 * x) mod (2^31 - 1)
47  * without overflowing 31 bits:
48  * (2^31 - 1) = 127773 * (7^5) + 2836
49  * From "Random number generators: good ones are hard to find",
50  * Park and Miller, Communications of the ACM, vol. 31, no. 10,
51  * October 1988, p. 1195.
52  */
53  long hi, lo, x;
54 
55  /* Can't be initialized with 0, so use another value. */
56  if(*ctx == 0)
57  {
58  *ctx = 123459876;
59  }
60  hi = *ctx / 127773;
61  lo = *ctx % 127773;
62  x = 16807 * lo - 2836 * hi;
63  if(x < 0)
64  {
65  x += 0x7fffffff;
66  }
67  return (int)((*ctx = (unsigned long)x) % ((unsigned long)RAND_MAX + 1));
68 #endif /* !USE_WEAK_SEEDING */
69 }
#define RAND_MAX
Definition: stdlib.h:51

References RAND_MAX.

Referenced by __attribute__().

Variable Documentation

◆ next

unsigned long next = 1
static

Definition at line 34 of file rand.c.