http://www.cplusplus.com/doc/ascii/
According to the above, the ASCII code of 'a' is 0x61 (97), and of 'z' is 0x7A (122).
So let's say you rotate to 124 which is beyond 'z'. The result should be 'b' (98).
To get to the "correct" new value you do
'a' + (124 - 'z' - 1)
.
x = 'a' + 124 - 'z' - 1
x = 97 + 124 - 122 - 1
x = 98 |
34 35 36 37
|
if (c > 'z') //If over rotated correct it BUT doesn't work?
{
c = 'a' + c - 'z' - 1;
}
|
I've said it before in other threads and I will say it for as long as I need to:
ASCII arithmetic hackery is very lacking in elegance! Using this technique makes the code harder to understand and prone to errors.
A more elegant way is to use alphabets strings for substituting. Both strings start with the content
"abcd...z"
, then you rotate the second one by
rotnum preferably using the function
std::rotate().
alpha1 = "abcdefghijklmnopqrstuvwxyz"
alpha2 = "hijklmnopqrstuvwxyzabcdefg" // for rotnum == 7 |
After that you simply search for letters in the first, and use the index you found in the second.
Encrypt 'h': position in alpha1 is 7 (counting from 0).
Result: alpha2[7] = 'o'