-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnigma.cpp
More file actions
77 lines (72 loc) · 1.62 KB
/
Copy pathEnigma.cpp
File metadata and controls
77 lines (72 loc) · 1.62 KB
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
#include "Enigma.hpp"
Enigma::Enigma(int numberOfRotors)
{
this->numberOfRotors = numberOfRotors;
}
char Enigma::encode(char input)
{
char result = input;
result = plugboard.encode(result);
if(numberOfRotors > 0)
{
result = rotors[0].encode(result);
}
for(int i = 1; i < numberOfRotors; i++)
{
int index = to_int(result);
index -= rotors[i - 1].getOffset();
if(index < 0)
{
index = ALPHA_SIZE + index;
}
result = rotors[i].encode(to_char(index));
}
result = reflector.encode(result);
for(int i = numberOfRotors - 1; i >= 1; i--)
{
result = rotors[i].encodeBack(result);
result = to_char((to_int(result) + rotors[i - 1].getOffset()) % ALPHA_SIZE);
}
if(numberOfRotors > 0)
{
result = rotors[0].encodeBack(result);
}
bool rotate_next = true;
for(int i = 0; i < numberOfRotors && rotate_next;)
{
rotors[i].rotate();
if(rotors[i].getOffset() == 0)
{
i++;
}
else
{
rotate_next = false;
}
}
result = plugboard.encode(result);
return result;
}
void Enigma::addPlugboard(Plugboard p) noexcept
{
plugboard = p;
}
void Enigma::addRotor(Rotor rotor) noexcept
{
rotors.push_back(rotor);
}
void Enigma::operate()
{
char nextCharacter;
while(cin >> ws && cin >> nextCharacter)
{
if(isupper(nextCharacter))
{
cout << encode(nextCharacter);
}
else
{
throw range_error("Character is not an uppercase letter");
}
}
}