使用模与解密程序负数的问题 [英] Problem using modulo with negative numbers in decryption program

查看:138
本文介绍了使用模与解密程序负数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相当新的C,最近一直在做一个简单的加密/解密程序。我设法得到加密很好,但我已经打与解密的路障。

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.

相关code是如下:

加密(其中asciinum是字母ASCII值,以及k是的V @ genere键由移位)。

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

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

我想用一个类似的模型来解密(使用相同的密钥),但我用环绕26个字符不工作的时候asciinum是否定的,因为将是减去5 AK的情况下模方法从(即0)。

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).

解密尝试...

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

任何帮助将大大AP preciated。谢谢!

Any help would be greatly appreciated. Thanks!

推荐答案

在pre-C99 C,为负数的行为是实现定义。在C99开始,它的定义,但你要什么没有做。

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)

假设 asciinum 永远不能低于-26。

这篇关于使用模与解密程序负数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆