c# - 线性反馈移位寄存器效率

标签 c# bit-manipulation shift-register

我有以下代码实现线性反馈移位寄存器的移位操作:

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/

相关文章:

c++ - 如何制作面具

c++ - 将多个值存储在一个 int C++ 中的位操作

c - Galois LFSR - 如何指定输出位数

loading - 为什么这个移位寄存器没有在 VHDL 中正确加载?

c# - 什么是对话上下文?

c# - 如何通知子控件父控件发生变化

C# 从 ThreadStart().Start() 返回值

bit-manipulation - 不带+运算符的两个数字相加(澄清)

python - Micropython 链式移位寄存器的行为不符合预期

c# - ComboBox 项目到多个文本框