c++ - 模数不返回数字的余数

标签 c++

我正在尝试使用加法密码模拟蛮力攻击,我需要对某些数字使用模数,但是当我尝试使用模数运算符“%”时,我的代码似乎永远都行不通

#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/

相关文章:

c++ - 单例行为相关查询

c++ - boost::python 和 weak_ptr:东西消失了

NAO Robot 上的 C++ - 如何运行我的 C++ 代码?

c++ - 什么是 "cerr"和 "stderr"?

c++ - 为什么我不能在 Visual Studio 2013 下使用 FFTW 或 AMPFFT 获得有效的二维 FFT?

c++ - 结构 vector 只返回最后一个值

c++ - 这是初始化指针的正确方法吗?

c++ - 链接到旧版本的 gcc

c++ - 无法在 OpenCV 中打开共享对象文件 'libopencv_shape.so.3.1'

c++ - 为嵌入式 C/C++ 项目构建系统