开发者

Problem using modulo with negative numbers in decryption program

开发者 https://www.devze.com 2023-03-14 02:32 出处:网络
I\'m rather new to C and have recently been working on making a simple encryption/decryption program.I managed to get the encryption fine, but I\'ve hit a road block with the decryption.

I'm rather new to C and have recently been working on making a simple encryption/decryption program. I managed to get the encryption fine, but I've hit a road block with the decryption.

The relevant code is as follows:

Encryption (where asciinum is the ascii value for the letter, and k is the "vigenere" key to be shifted by).

//shifts lowerc开发者_StackOverflow中文版ase letters by key
    if (asciinum >= 97 && asciinum <= 123)
    {
        f = p % keylen;
        k = key[f];
        asciinum = (asciinum - 97) + k;
        asciinum = (asciinum % 26) + 97;
        letterc = (char) asciinum;
        //printf("%c\n", letterc);
        cipher[j] = letterc;
        p++;
    }

    //shifts uppercase letters by key
    if (asciinum >= 65 && asciinum <= 91)
    {
        f = p % keylen;
        k = key[f];
        asciinum = (asciinum - 65) + k;
        asciinum = (asciinum % 26) + 65;
        letterc = (char) asciinum;
        cipher[j] = letterc;
        p++;
    }

I want to use a similar model to decrypt (using the same key), but the modulo method I used to wrap around the 26 characters doesn't work when asciinum is negative, as would be the case in subtracting a k of 5 from a (i.e. 0).

Decryption attempt...

    //shifts uppercase letters by key
    if (asciinum >= 65 && asciinum <= 91)
    {
        f = p % keylen;
        k = key[f];
        asciinum = (asciinum - 65) - k;
        asciinum = (asciinum % 26) + 65;
        letterc = (char) asciinum;
        cipher[j] = letterc;
        p++;
    }

Any help would be greatly appreciated. Thanks!


In pre-C99 C, the behaviour of % for negative numbers is implementation-defined. In C99 onwards, it's defined, but doesn't do what you want.

The easiest way out is to do:

((asciinum + 26) % 26)

Assuming asciinum can never get lower than -26.


Instead of using asciinum % 26, use (asciinum + 26) % 26, this will have you using modulus on positive numbers, at the cost of an extra addition each time through the cycle.

0

精彩评论

暂无评论...
验证码 换一张
取 消