|
发表于 2005-3-21 21:56:16
|
显示全部楼层
贴一个C#的完整代码供参考:LFSR类以及相关调用代码
using System;
using bit = System.Byte;
namespace RDLibrary
{
// 线性反馈移位寄存器封装类
// 架构采用快捷的Galois实现
//
sealed class LFSR
{
private bool deBruijn; // 产生de Bruijn序列?
private uint stages; // 阶数
private uint minStages;
private uint maxStages;
private uint initialState; // 初始态
private uint state; // 当前态
private uint zeros; // 检测de Bruijn序列中连零的个数
private uint inputMask; // 输入端掩码
private uint polynomial; // 当前本原多项式
#region 本原多项式表,polynomials[0]对应于2阶LFSR,依此类推
public readonly uint[] polynomials =
{
0x00000003, 0x00000005, 0x00000009, 0x00000009,
0x00000021, 0x00000041, 0x00000071, 0x00000021,
0x00000081, 0x00000201, 0x00000941, 0x00001601,
0x00002A01, 0x00004001, 0x00006801, 0x00004001,
0x00000801, 0x00064001, 0x00020001, 0x00080001,
0x00200001, 0x00040001, 0x00B00001, 0x00400001,
0x03100001, 0x06400001, 0x02000001, 0x08000001,
0x25000001, 0x10000001, 0x46000001
};
#endregion
public bit Output
{
get { return (bit)(state & 1); }
}
public uint State
{
get { return state; }
}
public LFSR()
{
deBruijn = false;
minStages = 2;
maxStages = minStages + (uint)polynomials.Length - 1;
stages = maxStages;
polynomial = polynomials[stages - minStages];
inputMask = (uint)1 << (int)(stages - 1);
initialState = 1;
state = initialState;
zeros = 0;
}
public void ClockIt()
{
if ((state & 1) == 1)
{
if (deBruijn)
{
// run of zeros broken
zeros = 0;
}
state = (state ^ polynomial) >> 1;
state ^= inputMask;
}
else
{
if (deBruijn)
{
if (++zeros != stages - 1)
{
state >>= 1;
}
}
else
{
state >>= 1;
}
}
}
public void Reset(uint stages, uint initialState, bool deBruijn)
{
if (stages < minStages || stages > maxStages)
{
throw new Exception("Stages of LFSR is out of range!");
}
this.stages = stages;
polynomial = polynomials[stages - minStages];
inputMask = (uint)1 << (int)(stages - 1);
if (initialState == 0 || (stages < 32 && initialState >= ((uint)1 << (int)stages)))
{
throw new Exception("Initial state of LFSR is out of range!");
}
this.initialState = initialState;
state = initialState;
zeros = 0;
this.deBruijn = deBruijn;
}
}
}
// 产生随机数序列
public static void GenerateRandomBytes(byte[] bytesOut)
{
uint seed;
do
{
seed = (uint)DateTime.Now.Ticks; // based on system datetime
} while (seed == 0); // LFSR can not be fed with zero
LFSR prng = new LFSR(); // Pseudo-random number generator
prng.Reset(32, seed, false);
for (int i = 0; i < bytesOut.Length; i++)
{
bytesOut = 0;
for (int j = 0; j < 8; j++)
{
prng.ClockIt();
bytesOut >>= 1;
bytesOut ^= (byte)(prng.Output << 7);
}
}
} |
|