如何解决49 + 82 = -190? C++ ceasar shift
我正在研究加密消息的代码。首先,我像这样应用 Ceasar shift:
message[i] += offset;
在 i = 40 的情况下,offset 等于 49,message[40] 等于 82。所以 82 += 49 应该是 131。(我记录了之前和之后的每个值)而不是 131,message[40] 是现在 -190。
这是完整的代码:
string encode(vector<string> rotors,string message,int offset)
{
for (int i = 0; i < message.length(); i++)
{
message[i] += offset; // ceasar shift
while (message[i] > 'Z') message[i] -= 26; // in case the value of the letter is larger than Z go back to the beginning of the alphabet
for (int j = 0; j < rotors.size(); j++) // the other part of enigma encryption
{
message[i] = rotors[j][message[i] - 65];
}
offset++; // increase ceasar shift
}
return message;
}
rotors 是一个随机字母向量,向一个不超过 50 个字符的字符串发送消息,并为 ceasar 偏移偏移一个整数(如果这很重要)。
所以我的问题是: 为什么 82 + 49 是 -190?这不仅发生在我的 PC 上,而且发生在在线编译器上。
编辑:这仅适用于 i = 40 和偏移量 = 49 的这种特殊情况。在所有其他情况下(更大或更小),它按预期工作。
如果你想重现这个:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string encode(vector<string> rotors,int offset) {
for (int i = 0; i < message.length(); i++) {
message[i] += offset;
while (message[i] > 'Z') message[i] -= 26;
for (int j = 0; j < rotors.size(); j++) {
message[i] = rotors[j][message[i] - 65];
}
offset++;
}
return message;
}
int main()
{
string message;
int pseudoRandomNumber;
vector<string> rotors;
cin >> pseudoRandomNumber; cin.ignore();
for (int i = 0; i < 3; i++) {
string rotor;
getline(cin,rotor);
rotors.push_back(rotor);
}
getline(cin,message);
message = decode(rotors,message,pseudoRandomNumber);
cout << message << endl;
}
复制这个并将其作为输入:
9
BDFHJLCPRTXVZNYEIWGAKMUSQO
AJDKSIRUXBLHWTMCQGZNPYFVOE
EKMFLGDQVZNTOWYHXUSPAIBRCJ
EVERYONEISWELCOMEHEREEVERYONEISWELCOMEHERE
解决方法
如果类型 char
表现为有符号字符类型,那么可以通过以下方式获得该类型对象中可以存储的最小值和最大值
#include <iostream>
#include <limits>
int main()
{
std::cout << static_cast<int>( std::numeric_limits<char>::min() ) << '\n';
std::cout << static_cast<int>( std::numeric_limits<char>::max() ) << '\n';
return 0;
}
程序输出为
-128
127
即 char
类型的对象无法存储值 131
。
如果以十六进制输出值131
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::hex << std::showbase << 131 << '\n';
return 0;
}
然后你会得到
0x83
二进制看起来像
10000011
正如所见,符号位已设置
10000011`
^
因此存储在 char
类型的对象中的这个值表示一个负数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。