Created
May 19, 2025 21:23
-
-
Save emmanuelrosa/59eb9497f14dc0b4afca6fa9c16b8e84 to your computer and use it in GitHub Desktop.
A 32-bit XOR Shift LFSR (Linear Feedback Shift Register).
This file contains hidden or 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
unsigned int XORShiftLinearFeedbackShiftRegister(unsigned int state, unsigned int seed, int index) { | |
/* A 32-bit XOR Shift LFSR. | |
* The lower 16 bits can be used as a pseudo random number generator. | |
* Based on the XORShift LFSR source code example at https://stackoverflow.com/questions/65661856/how-to-do-an-8-bit-16-bit-and-32-bit-linear-feedback-shift-register-prng-in-ja"; | |
* IMPORTANT: The seed must NEVER be zero, otherwise the LFSR will get stuck. | |
*/ | |
unsigned int lfsr = index == 0 ? seed : state; | |
lfsr ^= (lfsr & 0x0007ffff) << 13; | |
lfsr ^= lfsr >> 17; | |
lfsr ^= (lfsr & 0x07ffffff) << 5; | |
return lfsr; | |
} | |
// An example that generates 21 pseudo-random numbers. | |
// The number sequence is always the same; hence pseudo-random. | |
// Change the seed to change the starting point of the sequence. | |
int main() { | |
unsigned int state = 0; | |
unsigned int seed = 4294967295; // I simply asked Llama to generate a random unsigned int; NOTE: Must not be zero. | |
for(int i = 0; i < 20; i++) { | |
state = XORShiftLinearFeedbackShiftRegister(state, seed, i); | |
printf("%d\n", state); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment