在 C++ 中减去 ASCII character/values

Subtracting ASCII character/values in C++

这是我编写的代码的一个函数,它一遍又一遍地减去两个都是字符类型的值以获得文本,但结果不是字符串文本而是符号。

我通过 cout 检查 keyLettersanalysis 在 ASCII 中都有正确的值并在将它们转换为 int.

之前清除字母

lengthText 也正确。

keyLetters 是 5 个字母的单词。

void originalText(string analysis, string keyLetters) {
    int lengthText=analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i=0; i<lengthText; i++) {
        if(i%5==0)
            k=0;
        hold=keyLetters[k]-analysis[i];
        if (hold<=0) 
            hold*=-1;
        originText[i]=(char)hold;
        cout<<originText[i];
        k++;
    }

}

我得到的结果截图:

keyLettersanalysis都由'a'和'z'之间的字符组成。
这意味着这两个字符之间的差异可以从 -25 ('a' - 'z') 到 +25 ('z' - 'a').
然后你想用 ascii 字符表示这种差异,乘以 -1 负数。没有比这更简单的了:

void originalText(string analysis, string keyLetters) {
    int lengthText = analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i = 0; i < lengthText; i++) {
        if (i % 5 == 0) {
            k = 0;
        }
        hold = keyLetters[k] - analysis[i];
        if (hold < 0) {
            hold *= -1;
        }
        originText[i] = (char)hold + 'a';
        cout << originText[i];
        k++;
    }
}

您需要通过添加 'a' ascii 值(即 97)将 <0,25> 范围内的值转换为可打印的小 ascii 字符 <'a','z'>。 ascii 中的范围 <0,25> 只是控制字符。

这将导致:

The decrypted text:
oncegpmnahioethejewasalihtpegirpehmwantedhoplacallthedacandihedidnmtcareabmuhhejshudcahallinschomlherlarenhsgetangjcatherallhhetimebutihedidnmtcareabmuhhejparentifeelingiwhethejthecareangrymriadiheeaisgchabadgirplehuinohbeashejnefejeverhakecaremfevejchhingarogndcogsharhingfjoocogrlarenhstilpcogshudieiatichooltakealpthatieriogslcbestmfpucknmtheshorcdmesnohfiniihherethereismojetmihthatgirlonedaceenhtmschomlwhichiiuniveriitcactualpcbgtleolletendhosacabogtitschmolhhatihiimojecommonandidonnohknmwanyeacthatgirlofcogriewenhtognivejsitymrcollegeifihavetmsacwhenihegohopdejlikeehenshebecameeighheenceariopdsmahuniversitcthereeaiapotmfitudcforhejtodoehichihehohallcicrewgpsmshecjiedandcriedalohahnighhsfhejshecamhmmeandherkindpajentsasqedhejabmuhthereasmnforhejunitmppabpeteajsthaheairgnningouhfjomhejeyesconhinuogspchmwevejsherefgsedtmtellmrsacanyhhingiinceiheeantedtmshayalmnehhatnighthereishwasfglfilledsoathhahnighhshesleltaloneinthedarqeihhmutanconebesideihejtmeahchhejandtmtakecajeofherinhersleepingasshedidhoherlajenhsanditgdiesehenshewascoungersmthecccpehasgothejrogndshapnotfrmmnmwherebgtbecauseofareaionandthatjeaionisbecauiehhingieillcomebackholeolleafhejthecdidhheminanctimeeihhmutanceajningmralejt

至于为什么这没有给出正确的文本,我把它留给 OP,因为我没有得到这种加密方法。

整个程序:

#include <iostream>
#include <string>
#include <fstream>
#include <cmath>
using namespace std;
string encryptText(string, string);
string cryptanalyzeText(string);
void originalText(string, string);
int main() {
    string text, analysis;
    string key;
    text = "onceuponatimetherewasalittlegirlwhowantedtoplayallthedayandshedidnotcareaboutherstudyatallinschoolherparentsgetangryatherallthetimebutshedidnotcareaboutherparentsfeelingswhethertheyareangryorsadshewassuchabadgirlletusnotbeasherneverevertakecareofeverythingaroundyoustartingfromyourparentstillyoustudiesatschooltakeallthatseriouslybestoflucknothestorydoesnotfinishherethereismoretoitthatgirlonedaywenttoschoolwhichisuniversityactuallybutpeopletendtosayaboutitschoolthatitismorecommonandidonnotknowanywaythatgirlofcoursewenttouniversityorcollegeifihavetosaywhenshegotolderlikewhenshebecameeighteenyearsoldsoatuniversitytherewasalotofstudyforhertodowhichshetotallyscrewupsoshecriedandcriedalotatnightsftershecamhomeandherkindparentsaskedheraboutthereasonforherunstoppabletearsthatwasrunningoutfromhereyescontinuouslyhoweversherefusedtotellorsayanythingsinceshewantedtostayalonethatnightherwishwasfulfilledsoatthatnightshesleptaloneinthedarkwithoutanyonebesideshertowatchherandtotakecareofherinhersleepingasshedidtoherparentsandstudieswhenshewasyoungersothecyclehasgotherroundshapnotfromnowherebutbecauseofareasonandthatreasonisbecausethingswillcomebacktopeopleaftertheydidtheminanytimewithoutanywarningoralert";
    analysis = "qegegrfrafkdittgiiwmurpifvcigutcahayrrtqfkspxcpelxvyidmarrdejvhippfxcmtvebawkledukydkckelxkewctqfphqtgerqpkwgqvrrgdarxhqtrplfjvxiygsytejvhippfxcmtvebawkledrrvezvjjeqnzrgeyyittgixhqarvempxvyatjedejvaaeulghmdrhgutcpefwjrofdvestgirehgiivqtkekqerveahvzedaklizirvogpucogukerfkekfdqdcogtgerqpkwtunccogukydugjeteeysoxvroemncxhmvjiruqlwlkdvwtahcycwpfxhquksrkffiszqkjizkjlhqtvxhqtvmsyqiitakkxhmvxmrxqeidmaninfvfwctqfpwtktliewemvqtjmtkctxumnccbgvgiobnvxezfkssmarfogvzxsojfslfjrxifkjqodgtsmyqeenpkusnzqkonayrryicpxhmvxmrxqwgogtjiwqpkxogpzzeduzxyattslxgxiirkyevqvfwakyyinejvkofqchednzoeijvrstgsicmoviisjkiezavereqchsackynuxvvsuvpxhqtvaaeccstahjxupawsrtgixopqnliojjlefqkelxajgrqyltsauyicdkvhazftviqfrpofckrisjkwffgiwhqerqhaovenpjvvkuputadgexsmubidtgiebawkxhqtvesapwsrtgiynevftpmdcitqciwttckaaetlrnupxsufhismtgiiyqutsnfkeyogucchayvzeduyirqhlwepvfxexnfvsmarryfjzrgekegeejvaazvvhtaukeymnfrefjrxnuiyxhqtnmstyrwfgnwmlxguwomvklafpzkhfuyisxggxaxqeiizvyidmtbaifjfytmppsnqdvwipgjledvfaafeyledcehtavroeociiorjvvizjvvsxgvtizirwstgumdfqyirbciinfurrdevlhiqunlezuyiwmupsuzivvsavyickecihmuxsttgivogpuwhmrestrtfqnayyirqdlxbqerysqqwerqcjsnmpuxhmviiaeqemsngteuegklizijaixntsmqdrgkfqgiobnveffgixhqaumdfjvqizcectuovaifjfytmppaadpzrgatrpedv";

    cout<<"\n1- The original text:\n"<<text;
    cout<<"\n\nEnter a key of type string: ";
    key = "cream";
    cout<<endl;
    cout<<"The text after it has been encrypted:\n"<<encryptText(text, key)<<endl;

    cout<<"\n2- An encrpted text:\n"<<analysis;
    string keyLetters= cryptanalyzeText(analysis);
    cout<<"\n\nThe key is: "<<keyLetters<<endl<<endl;

    cout<<"The decrypted text:\n";
    originalText(analysis, keyLetters);
    cout<<endl<<endl;;

    return 0;
}
string encryptText(string text, string key) {
    int lengthText=text.length();
    int lengthKey=key.length();
    int count=0;

    for (int i=0; i<lengthText; i++) {
        text[i]=key[count];
        if (count<lengthKey-1)
            count++;
        else
            count=0;
    }
    return text;
}
string cryptanalyzeText(string analysis) {
    string keyLetters="aaaaa";
    char ch;
    int i;
    int lengthText=analysis.length();
    for (int keyPlace=0; keyPlace<6 ; keyPlace++) {
        int alphabet[26]={0};
        for (i=keyPlace; i<lengthText; i=i+5) {
            ch=analysis[i];
            alphabet[ch - 'a']++;
        }

        int max=alphabet[0];
        int maxPlace=0;
        for (int j=1; j<26; j++) {
            if(max<alphabet[j]) {
                max=alphabet[j];
                maxPlace=j;
            }
        }
        keyLetters[keyPlace]=maxPlace-4;
        if (keyLetters[keyPlace]<0) 
            keyLetters[keyPlace]+=26+97;
        else
            keyLetters[keyPlace]+=97;
    }
    return keyLetters;
}
void originalText(string analysis, string keyLetters) {
    int lengthText=analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i = 0; i < lengthText; i++) {
        if (i % 5 == 0) {
            k=0;
        }
        hold = keyLetters[k] - analysis[i];
        if (hold < 0) {
            hold *= -1;
        }
        originText[i] = (char)hold + 'a';
        cout << originText[i];
        k++;
    }
}

看来由于密文是由%26(mod26)生成的,所以大于26的字母值丢失了原来的值。所以当它们被解密时,它们被生成为不正确的字母。这就是为什么我必须 return 他们失去的 26,在做减法程序之前,因为它会被正确减去。

void originalText(string analysis, string keyLetters) {
    int lengthText=analysis.length();
    char originText[2000];
    int hold;
    int k;
    for (int i = 0; i < lengthText; i++) {
        if (i % 5 == 0) {
            k=0;
        }
        hold = (analysis[i]+26)-keyLetters[k];
        if (hold < 0) {
            hold *= -1;
        }
        hold%=26;
        originText[i] = (char)hold + 'a';
        cout << originText[i];
        k++;
    }
}

结果: