我正在尝试将matlab-函数bitxor移植到c++,以实现对std::c++的位异或操作。
现在我不确定这在一般情况下是否有效?如果我接受字符串并对单个字符执行XOR,则会观察到以下内容:
c=xor(a, b); d=xor(a, c)工作得很好,即d等于b。00110011,而int a=3是按位00000011。因此,"3“xor "2”返回一个不能显示但等于1的字符。有人知道--如果是的话--是否有可能在字符串上执行这种按位的XOR?它用于网络编码。
发布于 2013-09-16 14:41:04
如果要对字符串中的每个字符进行xor,只需遍历字符串并创建新的字符串:
std::string bitxor(std::string x, std::string y)
{
std::stringstream ss;
// works properly only if they have same length!
for(int i = 0; i < x.length(); i++)
{
ss << (x.at(i) ^ y.at(i));
}
return ss.str();
}
int main()
{
std::string a = "123";
std::string b = "324";
std::string c = bitxor(a, b);
std::string d = bitxor(c, b);
std::cout << a << "==" << d << std::endl; // Prints 123 == 123
return 0;
}https://stackoverflow.com/questions/18830505
复制相似问题