我正在尝试使用加法密码模拟蛮力攻击,我需要对某些数字使用模数,但是当我尝试使用模数运算符“%”时,我的代码似乎永远都行不通
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
char cipherText [15] = "UOISCXEWLOBDOX";
char guess [] = " ";
int numArray [15];
int modArray [15];
int finalArray[15];
char alpha [26] = {'A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//Get Number for each letter
for(int x = 0; x < sizeof(cipherText); x++)
{
char c = cipherText[x];
int num = 0;
for(int i = 0; i<sizeof(alpha);i++)
{
if(c == alpha[i])
{
num = num + 0;
break;
}
else
{
num = num + 1;
}
}
numArray[x] = num;
//cout<<" "<<numArray[x];
}
for(int i = 0; i < 26; i++)
{
cout<<endl;
for(int x = 0; x < 15; x++)
{
int j;
if(i == 0)
{
j = numArray[x];
}
else
{
j = numArray[x]-i;
}
modArray[x] = j;
//cout<<modArray[x]<<" ";
}
for(int x = 0; x < 15; x++)
{
int y = (modArray[x])%26;
cout<<modArray[x]<<" ";
}
cout<<endl;
}
}
输出保持为数字数组减去 i。我不知道为什么这不起作用任何帮助都会得到帮助。
最佳答案
您使用中间数组的解决方案过于复杂,并且您不必要地使用低级原语。代码可以变得非常简单:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
const std::string cipherText = "UOISCXEWLOBDOX";
constexpr int alphabetSize = 'Z' - 'A' + 1;
for(int i = 0; i < alphabetSize; i++) {
std::string encryptedText(cipherText.size(), ' ');
std::transform(cipherText.begin(), cipherText.end(), encryptedText.begin(),
[=](char c){
return ((c + i - 'A') % alphabetSize) + 'A';
}
);
std::cout << encryptedText << std::endl;
}
}
假设 'A' - 'Z'
的线性度范围,但您很难找到一台不这样做的机器。
这个假设允许代码的逻辑本质上浓缩到这一行:
return ((c + i - 'A') % alphabetSize) + 'A';
一开始可能看起来有点奇怪,但是一旦您意识到 -'A'
和 +'A'
零件只是为了将字符映射到 0-26 范围,以便可以使用模运算。您显然可以将其拆分为多个转换,分更多步骤进行(例如减去 'A'
,添加 i
,进行模运算,添加 'A'
)。
关于c++ - 模数不返回数字的余数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52638359/