我正在研究一种加密信息的代码。首先,我像这样应用Ceasar轮班:
message[i] += offset;在i= 40的情况下,偏移量等于49,message40 = 82。所以82 += 49应该是131。(我记录了之前和之后的每个值),而不是131,message40现在是-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;
}转子是随机字母的向量,传递不超过50个字符的字符串,并抵消ceasar移位的整数(如果这很重要)。
所以我的问题是:为什么在82 + 49中有190?这不仅发生在我的电脑上,也发生在在线编译器上。
编辑:这只适用于这种特殊情况,其中i= 40和偏移量= 49。在所有其他情况下(大的或小的),它都能按预期工作。
如果您想要复制这个:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string encode(vector<string> rotors, string message, 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发布于 2021-05-31 18:21:44
如果类型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类型对象中的值表示负数。
https://stackoverflow.com/questions/67778431
复制相似问题