-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLFSR.java
81 lines (69 loc) · 1.76 KB
/
LFSR.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class LFSR {
private boolean[] lfsr;
private int tap;
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
LFSR lfsr = new LFSR("01101000010", 8);
System.out.println("Testing step()");
for (int i = 0; i < 10; i++)
{
int bit = lfsr.step();
System.out.println(lfsr + " " + bit);
}
lfsr = new LFSR("01101000010",8);
System.out.println("\nTesting generate()");
for (int i = 0; i < 10; i++)
{
int r = lfsr.generate(5);
System.out.println(lfsr + " " + r);
}
}
public LFSR(String seed, int tap)
{
lfsr = new boolean[seed.length()];
this.tap = (seed.length()-1)-tap;
for(int i = 0; i < seed.length(); i++)
{
if(seed.charAt(i) == 48)
{
lfsr[i] = false;
}
else
{
lfsr[i] = true;
}
}
}
public int step()
{
boolean newBit = lfsr[0] ^ lfsr[tap];
for(int i = 0; i < lfsr.length-1; i++)
{
lfsr[i] = lfsr[i+1];
}
lfsr[lfsr.length-1] = newBit;
return newBit == false ? 0 : 1;
}
public int generate(int k)
{
int temp = 0;
for(int i = 0; i < k; i++)
{
temp *= 2;
temp += step();
}
return temp;
}
public String toString()
{
String representation = "";
for(int i = 0; i < lfsr.length; i++)
{
representation += lfsr[i] == false ? 0 : 1;
}
return representation;
}
}