I
I
Ivan Yakushenko2016-04-07 18:22:49
C++ / C#
Ivan Yakushenko, 2016-04-07 18:22:49

How does the Caesar cipher work in "C"?

There is a task in the "C" language to develop an encryption program using the Caesar algorithm. The formula itself is here:
ci = (pi + k) % 26
Actually, I could not apply this formula with respect to the application, I started looking for examples and came across the following options:

if(isupper(text[i])){
                text[i] = (text[i] - 'A' + k) % 26;
                text[i] = text[i] + 'A';
} else{
                text[i] = (text[i] - 'a' + k) % 26;
                text[i] = text[i] + 'a';
}

Either here:
if(islower(text[i]))
{
                printf("%c", ((((text[i] - 97)+k)%26)+97));
}
else
{
                printf("%c", ((((text[i] - 65)+k)%26)+65));
}

Their essence is the same, BUT. Please explain to me why we first subtract 'A' (the 65th character of the ASCII table) and then add it. Without this, the program stupidly displays nothing, although it does not produce errors.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2016-04-07
@kshnkvn

Subtract so that the codes count from 0 to 25.
Add to convert the code from 0 to 25 into characters from A to Z (and from a to z).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question