I'm working on an encrypter, and am using ASCII to Numbers and vice versa to scramble letters / numbers, but the numerical values on occasion come out negative!
Here's the (temporary) encryption/decryption algorithm so far. (it is nowhere near finished, just small steps)
void Encrypt()
{
cout << "Enter a message to encrypt" << endl;
string input;
int a;
int index = 0;
char output[255];
//chooses a starting point for the random key
a = rand() % 9;
cout << a << endl;
cin >> input;
//for each character in the input message
for (char ch : input)
{
int numeric = getNumber(ch);
numeric += a;
a += getNumber(ch);
//if the new numerical is greater than the maximum ascii size, reset
if (numeric > 255)
{
numeric -= 255 + 33;
}
output[index++] = getCharacter(numeric);
//moves the counter
if (a > 255)
{
a = 33;
}
}
//print the ascii equivalent of the 3 key values + 33
cout << getCharacter(a+33);
for (int c = 0; c < index; c++)
{
cout << output[c];
}
cout << endl;
}
void Decrypt()
{
string input;
char output[255];
cin >> input;
int index = 0;
for (char c : input)
{
output[index++] = c;
}
int a;
cout << getNumber(output[0]) << endl;
a = getNumber(output[0])-33;
cout << a << endl;
}
a represents a sort of key, and is outputted as the first value. Don't worry about unscrambling letters, haven't got there yet
int getNumber(char c)
{
return (int) c;
}
char getCharacter(int i)
{
return (char) i;
}
Also, here's an example of use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Type help for a list of commands
[Encrypter CLI]: encrypt
Enter a message to encrypt
5
hi
¸mÍ
[Encrypter CLI]: encrypt
Enter a message to encrypt
8
hi
·p┘
[Encrypter CLI]: decrypt
·p┘
-6
-39
[Encrypter CLI]:
Here's the (temporary) encryption/decryption algorithm so far. (it is nowhere near finished, just small steps)
I suggest you simplify the Encrypt function by removing the user input. Do the input in another function and pass your string into the function to be encrypted. Return the encrypted string so that you can call Decrypt() with the encrypted string.
//if the new numerical is greater than the maximum ascii size, reset
if (numeric > 255)
Note: ASCII is a 7 bit code, the maximum "ascii size" is 127, not 255. Also remember a signed character can't hold values over 127.