Add linear feedback shift register to generate "random" numbers.

This commit is contained in:
giomba 2023-10-22 11:39:02 +02:00
parent 99da9e2e4f
commit d3e2651212
2 changed files with 28 additions and 0 deletions

14
src/lfsr.c Normal file
View File

@ -0,0 +1,14 @@
#include "lfsr.h"
void lfsr_init(Lfsr *ctx, uint16_t init) {
ctx->lfsr = init;
ctx->bit = 0;
}
uint16_t lfsr_next(Lfsr *ctx) {
ctx->bit = ((ctx->lfsr >> 0) ^ (ctx->lfsr >> 2) ^ (ctx->lfsr >> 3) ^
(ctx->lfsr >> 5)) &
1U;
ctx->lfsr = (ctx->lfsr >> 1) | (ctx->bit << 15);
return ctx->lfsr;
}

14
src/lfsr.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef LFSR_H
#define LFSR_H
#include <stdint.h>
typedef struct Lfsr {
uint16_t lfsr;
uint16_t bit;
} Lfsr;
void lfsr_init(Lfsr *ctx, uint16_t init);
uint16_t lfsr_next(Lfsr *ctx);
#endif // LFSR_H