Algorithm
This is a implementation of the ROT-13 Ceaser Cipher.
To encrypt a string of alphabetic characters using ROT-13, take each character and move forward in the alphabet by 13 places, wrapping back to ‘A’ when ‘Z’ is encountered, ie: A becomes N, B becomes O, S becomes F, Z becomes M, etc.
Given that the alphabet has 26 letters, taking ROT-13 of a character and then taking ROT-13 of that character will yield the original character you started with. This means that the mapping between characters is two-way, so not only does A map to N, but N also maps to A. Because of this, ROT-13 is its own inverse function, meaning that it both encrypts and decrypts text.
Code Usage
ROT-13 is its own complement function, so the same function encrypts and decrypts. To en/decrypt a string, use the function rot13(), passing the string with the text to be rotated as the only argument.
Code
• Source Code • Sample Driver Program
Code Structure
To encrypt/decrypt a string with ROT-13, we follow a simple algorithm:
- For each character in the string, we first determine if it is in the ASCII alphabet range, if it isn’t, then we skip it.
- We then determine the character’s case (upper/lower).
- We increase the character’s value by 13 and check to see if it went past the Z value.
- If it did go past Z, then we take the amount that went over Z and we add to it the value of ‘A’ or ‘a’, depending on the character’s case.
Notes
This implementations assumes the character string is in ASCII.
ROT-13 has a couple of special cases that need to be addressed, namely, how numbers and punctuation are treated, and whether or not character case is preserved.
Different modifications of ROT-13 will sometimes apply “ROT-5″ (in the same vain as to ROT-13) to the numbers, and ROT-X (depending on the number of accepted characters) to the punctuation. This implementation sticks to the simple bare-bones ROT-13 and ignores all non-alphabetic characters. It also preserves the original case of the characters.