C++凯撒密码——理解ascii密钥

C++ caesar cipher — understanding ascii keys

本文关键字:ascii 密钥 理解 C++ 密码 凯撒      更新时间:2023-10-16

我目前正在做一个凯撒密码程序。它应该同时加密小写和大写。

例如如果我输入a,它会将键移动3,最终输出将变为d。

看看我的代码

char c;
c = (((97-52)+3) % 26) + 52;
cout << c;

字母"a"的ASCII代码为97。

所以通过正确的

1) ((97-52)+3) will give you 48
2) 48 % 26 will give you 8 since 48/26 will give you a remainder of 8.
3) 8 + 52 = 60(which will by right give you a value of '>' according to the ascii table)

但是我得到的输出是J,我不明白我得到的是"J"而不是">"的输出

我的想法可能是错误的,所以我需要帮助。

让我先链接我使用的ASCII图表:http://pl.wikipedia.org/wiki/ASCII网站是抛光的,但桌子本身是英文的。

我认为很明显,问题在于你使用的等式:

(((letter-52)+3) % 26) + 52;

实际上ASCII中的第一个字母是65(十六进制0x41-后面跟着提供的图表)。若ASCII中的字母块之间并没有字符,那个么使用模的想法就可以了。但也有(再次查看图表)。

这就是为什么你应该手动检查标志:

  1. 是大写字母:if (letter >= 0x41 && letter <= 0x5a)
  2. 是非资本:if (letter >= 0x61 && letter <= 0x7a)

通常在制作Ceasar密码时,您应该遵循以下步骤:

  1. 将大写字母替换为在字母表中移动给定数字的大写字母
  2. 如果字母超出了字母表的范围,则从字母表的开头开始继续迭代(X向右移动5将得到C)
  3. 其他字符保持不变

现在让我们实现这个(在代码中,我将使用字符的字母值-以避免错误):

#include <iostream>
#include <cstdlib>
using namespace std;
string Ceasar(string input, int offset)
{
string result = "";
for (int i = 0; i < input.length(); ++i)
{
// For capital letters
if (input[i] >= 'A' && input[i] <= 'Z')
{
result += (char) (input[i] - 'A' + offset) % ('Z' - 'A') + 'A';
continue;
}
// For non-capital
if (input[i] >= 'a' && input[i] <= 'z')
{
result += (char) (input[i] - 'a' + offset) % ('z' - 'a') + 'a';
continue;
}
// For others
result += input[i];
}
return result;
}
int main()
{
cout << Ceasar(string("This is EXamPLE teXt!?"), 8).c_str();
system("PAUSE");
}