Xorshift32

This commit is contained in:
2026-02-11 16:54:04 +01:00
parent feb4bd7fd4
commit 39d790a45c
3 changed files with 43 additions and 0 deletions

9
iris_c/main.c Normal file
View File

@@ -0,0 +1,9 @@
#include "random.h"
#include <stdio.h>
int main() {
set_random_seed(1842);
uint32_t num = random_u32();
printf("%u\n", num);
return 0;
}

24
iris_c/random.c Normal file
View File

@@ -0,0 +1,24 @@
#include "random.h"
static uint32_t state = 1;
void set_random_seed(uint32_t seed) {
state = seed ? seed : 1;
}
uint32_t random_u32(void) {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
return state;
}
uint32_t random_range(uint32_t max) {
if (max == 0) return 0;
uint32_t threshold = (0xFFFFFFFFU / max) * max;
uint32_t r;
do {
r = random_u32();
} while (r >= threshold);
return r % max;
}

10
iris_c/random.h Normal file
View File

@@ -0,0 +1,10 @@
#ifndef RANDOM_H
#define RANDOM_H
#include <stdint.h>
void set_random_seed(uint32_t seed);
uint32_t random_u32(void);
uint32_t random_range(uint32_t max);
#endif