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 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).
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.
不用使用asciinum % 26
,而使用(asciinum + 26) % 26
,这将使您对正数使用模数,但每次循环都需要额外加法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.