Skip to content

Instantly share code, notes, and snippets.

@mattrasband
Created November 9, 2019 18:04
Show Gist options
  • Save mattrasband/805d63ddc5a37c4f4b796b21c1d340e2 to your computer and use it in GitHub Desktop.
Save mattrasband/805d63ddc5a37c4f4b796b21c1d340e2 to your computer and use it in GitHub Desktop.
LFSR
from collections import deque
from typing import List
def fibonacci(seed: int, taps: List[int]):
"""Fibonacci Linear Feedback Shift Register"""
if not taps:
raise ValueError('Unable to create LFSR without taps.')
size = len(bin(seed)[2:])
if any(x > size for x in taps):
raise ValueError('Invalid tap provided, it exceeds the size of the seed.')
state = deque([int(x) for x in format(seed, f'0{size}b')], maxlen=size)
while True:
v = 0
for idx in reversed(taps):
v ^= state[idx - 1]
yield state.pop()
state.appendleft(v)
if __name__ == '__main__':
try:
for value in fibonacci(44257, [11, 13, 14, 16]):
print(value, end='')
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment