Here is a link to my assignment:
The user input and encrypting were easy, but I can't seem to decrypt the encryption. The job is to input one letter, it would go ahead ten letters(which would be the encryption), then go back ten letters (which would be the decryption.
I have tried messing around with the for loops but I did not really work.
#include <iostream>
using namespace std;
int main()
{
char m; //Declare character
cin >> m; // Input Character
int ma = (int)m; // Convert character to integer
int c; // Declare ciphertext
for (int i=0; i<=10; i++) {
c = ma + i;
if (c > 122) {
c = 97;
}
}
char cc = char(c);
cout << " " << endl;
cout << "You ciphertext is:" << endl;
cout << cc << endl;
int cb = (int)cc;
//cb = cb - 10;
int nm;
for (int b = 0; b>=10; b++) {
nm = cb - b;
if (nm < 97) {
nm = 122;
}
}
char mb = (char)nm;
cout << "You message is" << endl;
cout << mb << endl;
}
So here is what I expect: when I input "a" the ciphertext should be "k" and the decrypted message should be "a".
As I said in remark
for (int i=0; i<=10; i++) {
c = ma + i;
if (c > 122) {
c = 97;
}
}
does
{
int i = 10;
c = ma + i;
if (c > 122) {
c = 97;
}
}
because there c is reassigned so the previous turn as no impact on the current, and only the last counts.
Also
for (int b = 0; b>=10; b++) {
nm = cb - b;
if (nm < 97) {
nm = 122;
}
}
does nothing because the test b>=10
is immediately false b valuing 0
Independently of these errors the used encoding is not revertible for a lot of values, and there is no constraint on the character to encode, it can have any code supported by a char.
A simple way to encode and decode is to do a xor with a given value, whatever X for a given Y ((X^Y)^Y) == X)
, so the same way to encode and decode, just doing ^Y
in both case.
An other revertible way is a roll in one direction to encode then on the reverse direction to decode. Warning a roll, not a shift to not loose bits.
An other way is to encode exchanging some bits (for instance the lower 4 bits with the 4 higher ones supposing a char as at least 8 bits), and to do the same to decode.
Of course you can mix these ways rather than to just do one of them.
Of course you can use a way not based on a formula, for instance deciding for each letter an other one to replace it (a -> Z, b -> 0 etc and the reverse to decode)
There are an infinity of ways to encode/decode