简体   繁体   English

在解密程序中使用负数取模的问题

[英]Problem using modulo with negative numbers in decryption program

I'm rather new to C and have recently been working on making a simple encryption/decryption program. 我对C相当陌生,最近一直在致力于制作一个简单的加密/解密程序。 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). 加密(其中asciinum是字母的ascii值,k是要移动的“ vigenere”密钥)。

//shifts lowercase 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 ak of 5 from a (ie 0). 我想使用类似的模型解密(使用相同的密钥),但是当asciinum为负数时,我用来包装26个字符的取模方法不起作用,例如从(减去5的ak的情况下即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. 在C99 C之前的版本中,负数的%行为由实现定义。 In C99 onwards, it's defined, but doesn't do what you want. 在C99以后的版本中,它已定义,但没有执行您想要的操作。

The easiest way out is to do: 最简单的方法是:

((asciinum + 26) % 26)

Assuming asciinum can never get lower than -26. 假设asciinum永远不会低于-26。

不用使用asciinum % 26 ,而使用(asciinum + 26) % 26 ,这将使您对正数使用模数,但每次循环都需要额外加法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM