These are two simple and standard (and completely insecure, but this is a learning experience) ways to alter data in a reversible way.
The first one uses ch = ~ch; to toggle all of the bits in the character. So, for example, the letter a, which is ASCII 97 or binary 01100001, would become 10011110. This is reversible because you can apply exactly the same operation to the encrypted data to retrieve the original message.
The second is slightly more secure and uses the ^ (exclulsive-or) operator to alter the bits in each character based on a key: each bit in the message character is compared to the corresponding bit in the key character. If the bits are the same (either both 0 or both 1), the encrypted bit is 0. If the bits are different, the encrypted bit is 1. This is reversible because you can apply the same ^ operation again, using the same key, to retrieve the original message.
As a side note, all modern ciphers (such as DES3 and AES) are based on the exclusive-or operation, combined with an algorithm that "mixes" the bits in a specified way, so it's much harder to guess the key. The ciphertext can be decrypted by running the algorithm in reverse, or by taking computational short cuts that are mathematically equivalent.
Warning, and rant: This is clearly homework, and you've already admitted that both you and your friend are cheating by copying someone else's answer. As bad as that may be, it's even worse if you can't explain it, especially because I promise you that every other student who has ever taken the course and copied the answer will have produced these same 2 solutions. What's stupidly worse is that encryption is dead simple: it all comes down to flipping bits.
So here's the essence of cryptography:
- Take each character in the message.
- Modify the character somehow, according to some rule you invent. The important thing is that you must be able to reverse this rule, so for example, always setting the 3rd bit to
1 and the 6th bit to 0 won't work, because you'll no longer know what they originally were. But swapping the 3rd and 6th bits would be fine; you'd just swap them again to decrypt.
- Append the modified character to your output as the encrypted text.
- Repeat until you run out of characters.
To decrypt, follow the same algorithm, but reverse whatever rule you used to modify each character.
Uibu't bmm uifsf jt up ju. Hppe mvdl!