xorshift.c
1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Copyright (C) 2017 Kaspar Schleiser <kaspar@schleiser.de>
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*
* Code taken from Wikipedia (https://en.wikipedia.org/wiki/Xorshift)
*/
/**
* @ingroup sys_random
* @{
* @file
*
* @brief Xorshift random number generator implementation
*
* @author Kaspar Schleiser <kaspar@schleiser.de>
* @}
*/
#include <stdint.h>
#include <stdio.h>
#include "random.h"
/* The state word must be initialized to non-zero */
uint32_t xorshift32(uint32_t *state)
{
uint32_t x = *state;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
*state = x;
return x;
}
/* The state array must be initialized to not be all zero */
uint32_t xorshift128(uint32_t *state)
{
uint32_t t = state[3];
t ^= t << 11;
t ^= t >> 8;
state[3] = state[2];
state[2] = state[1];
state[1] = state[0];
t ^= state[0];
t ^= state[0] >> 19;
state[0] = t;
return t;
}
static uint32_t _state32;
uint32_t random_uint32(void)
{
return xorshift32(&_state32);
}
void random_init(uint32_t val)
{
printf("random init %u\n", (unsigned)val);
if (!val) {
val = 1;
}
_state32 = val;
}