C++凯撒密码——理解ascii密钥
C++ caesar cipher — understanding ascii keys
我目前正在做一个凯撒密码程序。它应该同时加密小写和大写。
例如如果我输入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中的字母块之间并没有字符,那个么使用模的想法就可以了。但也有(再次查看图表)。
这就是为什么你应该手动检查标志:
- 是大写字母:
if (letter >= 0x41 && letter <= 0x5a)
- 是非资本:
if (letter >= 0x61 && letter <= 0x7a)
通常在制作Ceasar密码时,您应该遵循以下步骤:
- 将大写字母替换为在字母表中移动给定数字的大写字母
- 如果字母超出了字母表的范围,则从字母表的开头开始继续迭代(X向右移动5将得到C)
- 其他字符保持不变
现在让我们实现这个(在代码中,我将使用字符的字母值-以避免错误):
#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");
}
相关文章:
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 允许从 std::map 的密钥窃取资源?
- TMap::Emplace() 在应用现有密钥时会覆盖吗?
- 在没有密钥的情况下读取密文的剩余噪声预算
- 如何修复无效的API密钥,IP或操作权限错误?
- 所有可能的链接生成器与64位密钥
- 如何在unordered_map中更改密钥?
- 获取当前密钥状态?
- curl_easy_perform() 失败:SSL 对等证书或 SSH 远程密钥不正常
- 将密钥发送到非前台的游戏窗口
- 有哪些方法可以对基于 256 位密钥的矩阵进行加扰?
- 如何在精灵表上的两个不同部分之间来回切换,同时用户仍使用 SFML 持有密钥
- 如何将CNG密钥转换为OpenSSL EVP_PKEY(反之亦然)?
- 运行密钥密码解密知道密钥?
- std::unordered_map 运算符 [] 是否对非现有密钥进行零初始化?
- 封装 std::map 以允许迭代,但没有直接密钥访问?
- 如果我使用同一个密钥推送用户数据两次,会发生什么
- 如何在C++中创建自己的编译密钥
- 重载std::映射不同的密钥类型
- C++凯撒密码——理解ascii密钥