我正在为C中的一个类加密程序。我使用modulo 27数学来执行加密。我将每个加密的字符添加到一个数组中,但我注意到未打印的字符也会在最后添加到我的字符串中。当我检查加密文本的字数时,我意识到这一点,它包含的字符多于加密的原始文本。任何人都可以解释为什么会这样吗?这考虑了文本末尾的换行符。
Plaintext = THE RED GOOSE FLIES AT MIDNIGHT STOP - wc is 37
Ciphertext = ACBVKWNOGMMMPQHNI XL QBJXDPNVIQVSNZN - wc is 40
//Go through each character of the plaintext
for (i = 0; i < size; i++)
{
//Convert the characters to an integer
PlainNums[i] = charInt(plaintext[i]);
KeyNums[i] = charInt(key[i]);
//Add the int from plain text and the key together
CipherNums[i] = PlainNums[i] + KeyNums[i];
if (CipherNums[i] > 27) //Wrap around if the number exceeds 27
{
CipherNums[i] -= 27;
}
CipherNums[i] = CipherNums[i] % 27; //Use modulo 27 math to generate a new integer
cipherText[i] = IntChar(CipherNums[i]);
}
int charInt(char c)
{
switch (c)
{
case 'A': return 0;
case 'B': return 1;
case 'C': return 2;
case 'D': return 3;
case 'E': return 4;
case 'F': return 5;
case 'G': return 6;
case 'H': return 7;
case 'I': return 8;
case 'J': return 9;
case 'K': return 10;
case 'L': return 11;
case 'M': return 12;
case 'N': return 13;
case 'O': return 14;
case 'P': return 15;
case 'Q': return 16;
case 'R': return 17;
case 'S': return 18;
case 'T': return 19;
case 'U': return 20;
case 'V': return 21;
case 'W': return 22;
case 'X': return 23;
case 'Y': return 24;
case 'Z': return 25;
case ' ': return 26;
default: return -1;
}
}
char IntChar(int n)
{
switch(n)
{
case 0: return 'A';
case 1: return 'B';
case 2: return 'C';
case 3: return 'D';
case 4: return 'E';
case 5: return 'F';
case 6: return 'G';
case 7: return 'H';
case 8: return 'I';
case 9: return 'J';
case 10: return 'K';
case 11: return 'L';
case 12: return 'M';
case 13: return 'N';
case 14: return 'O';
case 15: return 'P';
case 16: return 'Q';
case 17: return 'R';
case 18: return 'S';
case 19: return 'T';
case 20: return 'U';
case 21: return 'V';
case 22: return 'W';
case 23: return 'X';
case 24: return 'Y';
case 25: return 'Z';
case 26: return ' ';
default: return '!'; //error
}
}
答案 0 :(得分:1)
尝试在循环结束时添加cipherText[size] = '\0';
以确保编码的字符串仅包含编码数据。
答案 1 :(得分:0)
使用代码中的cipherText
在for
loop
之前初始化memset
,如下所示。
memset(cipherText,0,sizeof(cipherText));
for (i = 0; i < size; i++)
{
//Convert the characters to an integer
PlainNums[i] = charInt(plaintext[i]);
//....
// rest of the code
您必须include<string.h
。
它有效。