Skip to content

Commit

Permalink
rand: add prng
Browse files Browse the repository at this point in the history
This commit adds the ability to use random numbers with a seed, via the
known methods rand() and srand().

As generator, a simple linear congruential generator is used, with the
same parameters as used in musl or newlib.

Signed-off-by: Norbert Manthey <[email protected]>
  • Loading branch information
nmanthey committed Sep 29, 2020
1 parent ed189f8 commit 8e03420
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions include/lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -385,4 +385,8 @@ static inline unsigned int next_power_of_two(unsigned int n) {

extern void halt(void);

extern void srand(unsigned s);

extern int rand(void);

#endif /* KTF_LIB_H */
13 changes: 13 additions & 0 deletions lib/lib.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,16 @@ void __noreturn halt(void) {
pause();
}
}

static uint64_t seed;

void srand(unsigned s)
{
seed = s-1;
}

int rand(void)
{
seed = 6364136223846793005ULL*seed + 1;
return seed>>33;
}

0 comments on commit 8e03420

Please sign in to comment.