XOR错误的结果,转义字符

XOR wrong result , escaping char

本文关键字:转义字符 结果 错误 XOR      更新时间:2023-10-16

我正在尝试对一个小字符串进行异或,它可以工作。当我尝试使用XOR字符串时,我甚至无法编译它

 string str = "MyNameIsMila";
 string str_xored = "2*&.8"'*"; //you can't escape this or the result be be different 
 //Enc:2*&.8"'*:
 //Dec:MyNameIsMila:

我试图逃脱这根绳子,但最后我得到了另一个结果。有什么好的方向吗?退出后输出:

//Enc:yamesila:
//Dec:2*&.8"'*:

希望能让MyNameIsMila回来。

功能看起来像:

 string encryptDecrypt(string toEncrypt) {
     char key = 'K'; //Any char will work
     string output = toEncrypt;   
     for (int i = 0; i < toEncrypt.size(); i++)
         output[i] = toEncrypt[i] ^ key;
     return output;
 }

我有两件事要说:

1:字符串的值需要在2->"之间

 string str_xored = 2*&.8"'*;   //this is not a valid syntax = error
 //valid
 string str_xored = "2*&.8";
 str += '"';
 str += "'*";

2:在你的情况下,我会使用迭代器:

#include <iostream>
#include <string>
//please don't use "using namespace std;"
 std::string encryptDecrypt(std::string toEncrypt) {
     char key = 'K';            //Any char will work
     std::string output = "";   //needs to be   empty   
     for (auto i = toEncrypt.begin(); i != toEncrypt.end(); i++) {
        output += *i ^ key;     //*i holds the current character to see how
                                //an iterator works have a look at my link
     }
     return output;
 }

int main() {
    std::string str = encryptDecrypt("Hello...!");
    std::cout << str << std::endl;
    return 0;
}

下面来看一下(字符串)迭代器:

链路1

链路2

如果你认为迭代器太难了,那么就使用

for(int i = 0; i < str.size(); i++){
    //CODE
}

for()-循环

不能像对待普通字符串那样对待xored字符串!

value ^ same_value == 0

把它们当作普通的容器。

示例:

#include <iostream>
#include <iterator>
#include <algorithm>
template<typename InputIterator, typename OutputIterator, typename Key>
void perform_xor(InputIterator begin, InputIterator end, OutputIterator out, Key const &key) {
    std::transform(begin, end, out, [key](auto &&value) { 
        return value ^ key;
    });
}
using namespace std;
int main() {
    char test[] = "(2*&.8"'*";
    perform_xor(begin(test), end(test), begin(test), '&');
    copy(begin(test), end(test), ostream_iterator<int>(cout, " ")); 
    cout << endl;
    perform_xor(begin(test), end(test), begin(test), '&');
    copy(begin(test), end(test), ostream_iterator<char>(cout)); 
    return 0;
}

请参阅:http://ideone.com/ryoNp5