C++ 字符串上的 Bitxor

bitxor on c++ strings

本文关键字:Bitxor 字符串 C++      更新时间:2023-10-16

我正在尝试将matlab函数bitxor移植到c ++,以实现对std::strings的按位XOR运算。

现在我不确定这是否真的普遍有效?如果我获取字符串并对单个字符执行 XOR,我会观察到以下内容:

  • c=xor(a, b); d=xor(a, c)工作正常,即 d等于b
  • "3"是按位00110011int a=3是按位00000011。因此,"3"xor "2"返回一个无法显示但等于 1 的字符。

有谁知道 - 如果是的话如何 - 是否可以在字符串上执行这种按位 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;
}