异或是一种二进制的位运算,符号以 XOR 或 ^ 表示。
1.1运算规则
相同为0,不同为1,即
1 ^ 1 = 0
0 ^ 0 = 0
1 ^ 0 = 1
由运算规则可知,任何二进制数与零异或,都会等于其本身,即 A ^ 0 = A。
1.2 异或性质
(1)交换律: A ^ B = B ^ A
(2)结合律: ( A ^ B ) ^ C = A ^ ( B ^ C )
(3)自反性: A ^ B ^ B = A (由结合律可推: A ^ B ^ B = A ^ ( B ^ B ) = A ^ 0 = A)
1.3 加解密字符串
#include <string>
#include <iostream>using namespace std;int key[] = { 1,2,3,4,5,6,7,8};void encryption(string& c, int key[]) {int len = c.size();for (int i = 0; i < len; i++) {c[i] = c[i] ^ key[i % 8];}
}
void decode(string& c, int key[]) {int len = c.size();for (int i = 0; i < len; i++) {c[i] = c[i] ^ key[i % 8];}
}int main(int argc, char* argv[]) {std::string str = "This is raw string!";std::cout << "原文:" << str << std::endl;encryption(str, key);std::cout << "加密后密文:" << str << std::endl;decode(str, key);std::cout << "解密后密文:" << str << std::endl;return 0;
}