0

I'm don't understand how to use modulo to shift my characters. When I type 'Z', I get a '[' instead of 'A'. I read elsewhere that I need to shift the key AND the inputed text - yes?

for (int i = 0, n = strlen(p); i < n; i++)
{
    if (isalpha(p[i]))
    {
        if (isupper(p[i]))
        {
        char stringshifttext = ((p[i] + (k[i]-'A') % 26) + p[i]);
        printf("%c", stringshifttext);
        }
    }
}
2

In order to use modulo to wrap around the dictionary you first need to offset both key and plaintext to convert them to values between 0 and 25, and then add them and use modulo. That part is just as it is in caesar, with the only difference that instead of converting only the plaintext, you need to convert both because the key is also an ASCII character, instead of a number.

1

You were correct. You must use the modulus operator to ensure that the text output is between A and Z. However, you are wrapping the key, so that it is from A to Z. You must wrap the output. So instead of

(p[i] + (k[i]-'A') % 26) + p[i]

Use something like

((p[i] - 'A') + (k[i] - 'A')) % 26 + 'A'

To first add up the distances from A, ensure this sum of the distances is less than 26 and add the new distance from A... to A itself.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .