rot13 , To add 13 or subtract 13? - kevshouse/exam_quest GitHub Wiki

The Logic Behind the ROT13 +13 / -13 Calculation

The logic behind the +13 / -13 calculation is a clever and efficient way to handle the "wrap-around" nature of the alphabet without using more complex math like the modulo operator (%).

Let's break it down.

The Foundation: Characters are Numbers

First, it's essential to remember that computers see characters as numbers. The most common encoding for this is ASCII. In ASCII:

  • 'a' is 97, 'b' is 98, ..., 'm' is 109, 'n' is 110, ..., 'z' is 122.
  • 'A' is 65, 'B' is 66, ..., 'M' is 77, 'N' is 78, ..., 'Z' is 90.

The letters in each case (upper and lower) are in a perfect, contiguous block of numbers. This allows us to do math on them.

The Problem: Wrapping Around the Alphabet

The alphabet has 26 letters. ROT13 means "rotate by 13 places".

  • For a letter in the first half of the alphabet (like 'a'), adding 13 works perfectly.
    • 'a' (97) + 13 = 110, which is the ASCII code for 'n'. Correct.
  • For a letter in the second half (like 'p'), adding 13 fails.
    • 'p' (112) + 13 = 125, which is the ASCII code for '{'. Incorrect. We want it to wrap around and become 'c'.

This "wrap-around" is the central problem we need to solve.

The Solution: Splitting the Alphabet

The +13 / -13 trick works by treating the alphabet as two distinct halves.

1. The First Half (A-M and a-m)

  • Logic: If you take any letter from the first half and add 13, the result will never go past 'Z' or 'z'. It will always land correctly in the second half of the alphabet.
  • Rule: If the character is between 'a' and 'm' (or 'A' and 'M'), add 13.

Example: c -> p

  1. Character is 'c'.
  2. Is it between 'a' and 'm'? Yes.
  3. Action: Add 13.
  4. Calculation: 'c' (99) + 13 = 112.
  5. Result: 112 is the ASCII code for 'p'. Correct.

2. The Second Half (N-Z and n-z)

  • Logic: If you take any letter from the second half, adding 13 will always go past the end of the alphabet. However, a rotation of +13 places is the exact same as a rotation of -13 places (since 13 is exactly half of 26). By subtracting 13, you are effectively wrapping around the alphabet in the other direction.
  • Rule: If the character is between 'n' and 'z' (or 'N' and 'Z'), subtract 13.

Example: p -> c

  1. Character is 'p'.
  2. Is it between 'n' and 'z'? Yes.
  3. Action: Subtract 13.
  4. Calculation: 'p' (112) - 13 = 99.
  5. Result: 99 is the ASCII code for 'c'. Correct.

Summary

This method is elegant because it avoids complex calculations. You just need two simple if/else if checks for each case (lowercase and uppercase).

// For a given character `c`

if (c >= 'a' && c <= 'm') {
    c = c + 13;
} else if (c >= 'n' && c <= 'z') {
    c = c - 13;
} else if (c >= 'A' && c <= 'M') {
    c = c + 13;
} else if (c >= 'N' && c <= 'Z') {
    c = c - 13;
}

This is the most direct and computationally simple way to implement ROT13, which is why it's the standard solution.