簡體   English   中英

在解密程序中使用負數取模的問題

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

我對C相當陌生,最近一直在致力於制作一個簡單的加密/解密程序。 我設法對加密進行了改進,但解密遇到了障礙。

相關代碼如下:

加密(其中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++;
    }

我想使用類似的模型解密(使用相同的密鑰),但是當asciinum為負數時,我用來包裝26個字符的取模方法不起作用,例如從(減去5的ak的情況下即0)。

解密嘗試...

    //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++;
    }

任何幫助將不勝感激。 謝謝!

在C99 C之前的版本中,負數的%行為由實現定義。 在C99以后的版本中,它已定義,但沒有執行您想要的操作。

最簡單的方法是:

((asciinum + 26) % 26)

假設asciinum永遠不會低於-26。

不用使用asciinum % 26 ,而使用(asciinum + 26) % 26 ,這將使您對正數使用模數,但每次循環都需要額外加法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM