如何用C语言实现带有字节元素数组的128位线性反馈移位寄存器
我有一个如下数组,
unsigned char A[16]
我使用这个数组来表示 128 位硬件寄存器。现在我想使用这个长寄存器实现一个线性反馈移位寄存器(LFSR,斐波那契实现)。连接到该 LFSR 反馈同或门的多项式(或抽头)为 [128, 29, 27, 2, 1]。
16 位 LFSR 的实现(抽头位于 [16, 14, 13, 11])可以从 获得维基百科如下。
unsigned short lfsr = 0xACE1u;
unsigned bit;
unsigned rand()
{
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
return lfsr = (lfsr >> 1) | (bit << 15);
}
然而,就我而言,我需要将位从一个字节元素转移到另一个字节元素,例如,需要将 msb 或 A[0] 转移到 A1。完成此转变的最少编码是什么? 谢谢你!
I have an array as follows,
unsigned char A[16]
I am using this array to represent a 128-bit hardware register. Now I want to implement a linear feedback shift register (LFSR, Fibonacci implementation) using this long register. The polynomials (or tap) which connect to the feedback xnor gate of this LFSR are [128, 29, 27, 2, 1].
The implementation of a 16-bit LFSR (taps at [16, 14, 13, 11]) can be obtained from Wikipedia as the following.
unsigned short lfsr = 0xACE1u;
unsigned bit;
unsigned rand()
{
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
return lfsr = (lfsr >> 1) | (bit << 15);
}
In my case, however, I need to shift bits from one byte element to another, e.g. the msb or A[0] need to be shift to the lsb of A1. What is minimum coding to do this shift?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要计算要移入的位,您不需要每次都移动整个数组,因为您只对一位感兴趣(请注意
bit = 末尾的
行来自维基百科)。& 1
正确的移位量是:
所以,
现在,您确实需要移位:
您可以通过使用 uint32_t 或 uint64_t 而不是无符号字符来提高效率(取决于你的处理器字大小),但原理是一样的。
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 thebit =
line from Wikipedia).The right shift amounts are:
So,
Now, you really need to shift in the bit:
You can make this a bit more efficient by using
uint32_t
oruint64_t
instead of unsigned chars (depending on your processor word size), but the principle is the same.