# Reverse output of general Fibonacci LFSR

Suppose we have some Fibonacci LFSR, and it outputs some sequence.

How to change starting LFSR so, that it outputs exactly same sequence, but in reverse order?

The Fibonnacci LFSR whose feedback polynomial is the reverse of the given LFSR polynomial will produce the sequence in reverse. Here by reverse is meant $x^mg(x^{-1})$ where $g(x)$ (of degree $m$) is the feedback polynomial of the given Fibonnacci LFSR. Note that the initial loading of the LFSR must be changed to the ending of the given output sequence (in reverse order).

Provide codes for lfsr and reversed lfsr here. The first is code from wikipedia for lfsr, and the second is the reversed lfsr.

#include <stdio.h>

int main(void)
{
unsigned short start_state = 0xace1;
unsigned lfsr = start_state;
unsigned int period = 0;

do
{
unsigned short lsb = lfsr & 1;
lfsr >>= 1;
lfsr ^= (-lsb) & 0xb400;
++period;

printf("%x\n", lfsr);
} while (lfsr != start_state);

return 0;
}


#include <stdio.h>

unsigned short bit_revert(unsigned short v)
{
int i = 0;
unsigned short lsb = 0;
unsigned short n = 0;

for (i = 0; i < sizeof(unsigned short) * 8; i++)
{
lsb = v & 1;
v >>= 1;
n <<= 1;
n |= lsb;
}

return n;
}

int main(void)
{
unsigned short start_state = 0xace1;
unsigned lfsr = start_state;
unsigned int period = 0;

do
{
unsigned short lsb = lfsr & 1;
lfsr >>= 1;
lfsr ^= (-lsb) & 0x8016;
++period;

printf("%x\n", bit_revert(lfsr));
} while (lfsr != start_state);

return 0;
}