libc: Add rand() + srand()
All checks were successful
continuous-integration/drone/push Build is passing

Very basic random number generator, but that's what rand() is.
If you want secure numbers then use arc4random() or something idk
This commit is contained in:
apio 2023-05-02 21:20:24 +02:00
parent d9b7e8edc0
commit a0b45a51de
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 19 additions and 1 deletions

View File

@ -29,6 +29,8 @@ typedef struct
#define MB_CUR_MAX 4 #define MB_CUR_MAX 4
#define RAND_MAX 32767
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C"
{ {
@ -91,8 +93,11 @@ extern "C"
* endptr if nonnull. */ * endptr if nonnull. */
unsigned long strtoul(const char* str, char** endptr, int base); unsigned long strtoul(const char* str, char** endptr, int base);
/* Return the next pseudorandom number. */
int rand(); int rand();
void srand(int);
/* Set the pseudorandom number generator's seed, which will determine the sequence of numbers returned by rand(). */
void srand(unsigned int seed);
/* Exit the program normally, performing any registered cleanup actions. */ /* Exit the program normally, performing any registered cleanup actions. */
__noreturn void exit(int status); __noreturn void exit(int status);

View File

@ -205,4 +205,17 @@ extern "C"
{ {
c_quicksort(base, nmemb, size, compar); c_quicksort(base, nmemb, size, compar);
} }
static unsigned next = 42;
int rand()
{
next = next * 1103515245 + 12345;
return (int)((unsigned)(next / 65536) % 32768);
}
void srand(unsigned int seed)
{
next = seed;
}
} }