I am coding in "C", and I am implementing the caesar cypher, and the value of each letter must remain within the bounds of capital letters (if the letter is uppercase) or lowercase letters (if the letter is lowercase) on the ASCII chart. How do I account for the case where the decimal value of some uppercase character in ASCII is shifted to a number exceeding 90 ('Z' in ASCII) or the decimal value of a lowercase character in ASCII is shifted to a number exceeding 122 ('z' in ASCII)?
(Edited answer to not give away entire solution after noticing this is for CS50)
Assuming plaintext
is a char array containing the phrase you wish to encrypt using the caesar cipher and shiftValue
is the number of places you wish to rotate the plain alphabet, below are
pieces of code addressing your question:
(plaintext[i] - 65 + shiftValue) % 26 + 65 // adjust for uppercase letters
(plaintext[i] - 97 + shiftValue) % 26 + 97 // adjust for lowercase letters
Let's first consider what we're doing when we adjust for uppercase letters. Let's say that the letter we're currently encrypting (plaintext[i]
) is 'Y' and our shift/rotation value is 2. For right now, assume the uppercase alphabet is enumerated as 0 through 25 i.e. A = 0, B = 1,..., Y = 24, Z = 25. Now let's shift the alphabet by 2. Then, A = 2, B = 3,..., Y = 26, Z = 27. However, we only have alphabetical characters enumerated 0 through 25, so what we need to do to "wrap" the shift (i.e. make sure that the corresponding numerical value of 'Y' is within the range [0, 25]) is take the value mod 26. Of course, uppercase characters in ASCII are enumerated 65 through 90, so to apply this logic, we convert the enumeration from [65, 90] to [0, 25] by subtracting 65 from the ASCII value of each uppercase letter. After we've applied the shift, we add 65 back to convert back to ASCII. The logic is the same for lowercase letters except the way in which lowercase characters are enumerated in ASCII is obviously different from uppercase characters.