我有以下代码实现线性反馈移位寄存器的移位操作:
public int DoShift()
{
//Find new top bit
int feedback = Contents & tapSequence;
int newBit = 0;
for(int i = 1; i <= length; i++)
{
newBit = 1 & (newBit ^ feedback);
feedback >>= 1;
}
//Remember falloff, shift register, add new bit
int result = Contents & 1;
Contents >>= 1;
Contents += newBit << (length - 1);
return result;
}
哪里
- Contents 是寄存器的当前内容
- tapSequence 是 XOR 抽头序列,其中 1 表示抽头位,0 表示未抽头位。
- length 是寄存器的位数。
但是,运行 CPU 使用率测试后,该函数占用了我多达 60% 的运行时间(我认为这是一个相当轻量级的方法)。有没有更有效的方法来写这个? 有没有办法将 int 的内容与其自己的位进行异或(从而消除 for 循环)?
最佳答案
试试这个:
public int DoShift()
{
int newBit = 1 << (length - 1); // you can save it as class member
int result = Contents & 1;
int feedback = Contents & tapSequence;
Contents >>= 1;
while(feedback != 0) {
feedback &= feedback - 1;
Contents ^= newBit;
}
return result;
}
此外,还存在更有效的方法,称为“反向LSFR”。它的想法是 - 如果结果为 1,则将 tapSequence 应用于整个寄存器一次。
参见示例:https://en.wikipedia.org/wiki/Linear_feedback_shift_register
关于c# - 线性反馈移位寄存器效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895629/