Created
March 2, 2018 02:45
-
-
Save dvigne/efac28f4889664acc790555c612b7b4b to your computer and use it in GitHub Desktop.
A 16 LFSR with start state detection and pooling from the current system uptime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////////////////////////////////////////////////////////////////////////// | |
// | |
// randomNum takes void arguments and gets its random seed from the current | |
// uptime of the system | |
// | |
/////////////////////////////////////////////////////////////////////////////// | |
int randomNum(void) { | |
static uint16_t start_state = 0; | |
static uint16_t lfsr = 0; | |
if (lfsr == start_state) { | |
start_state = 0; | |
lfsr = 0; | |
} | |
/* Any nonzero start state will work. */ | |
start_state = (start_state == 0) ? start_state = (uint16_t) sys_uptime() : start_state; | |
lfsr = (lfsr == 0) ? lfsr = start_state : lfsr; | |
uint16_t bit; /* Must be 16bit to allow bit<<15 later in the code */ | |
unsigned period = 0; | |
do | |
{ | |
/* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */ | |
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1; | |
lfsr = (lfsr >> 1) | (bit << 15); | |
++period; | |
} while (lfsr > MAX); | |
return lfsr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment