如何在C中使用字节元素数组实现128位线性反馈移位寄存器

StackOverflow https://stackoverflow.com/questions/7830379

  •  27-10-2019
  •  | 
  •  

我有一个如下数组,

unsigned char A[16]

我正在使用此数组表示一个128位硬件寄存器。现在,我想使用此长寄存器实现线性反馈移位寄存器(LFSR,斐波纳契实现)。连接到此LFSR的反馈xnor门的多项式(或抽头)为[128、29、27、2、1]。

可以从维基百科如下。 通用标签

但是,就我而言,我需要将位从一个字节元素转移到另一个字节元素,例如必须将msb或A [0]移至A 1 的lsb。进行此转换的最低编码是多少? 谢谢!

有帮助吗?

解决方案

To calculate the bit to shift in you don't need to shift the whole array every time since you are only interested in one bit (note the & 1 at the end of the bit = line from Wikipedia).

The right shift amounts are:

128 - 128 =   0   => byte  0 bit 0
128 -  29 =  99   => byte 12 bit 3
128 -  27 = 101   => byte 12 bit 5
128 -   2 = 126   => byte 15 bit 6
128 -   1 = 127   => byte 15 bit 7

So,

bit = ((A[0] >> 0) 
    ^  (A[12] >> 3) 
    ^  (A[12] >> 5) 
    ^  (A[15] >> 6) 
    ^  (A[15) >> 7)) & 1;

Now, you really need to shift in the bit:

A[0] = (A[0] >> 1) | (A[1] << 7);
A[1] = (A[1] >> 1) | (A[2] << 7);
// and so on, until
A[14] = (A[14] >> 1) | (A[15] << 7);
A[15] = (A[15] >> 1) | (bit << 7);

You can make this a bit more efficient by using uint32_t or uint64_t instead of unsigned chars (depending on your processor word size), but the principle is the same.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top