0

我正在尝试将 matlab 函数移植bitxor到 c++ 以在 std::strings 上实现按位异或运算。

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

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

有谁知道 - 如果是的话 - 是否可以对字符串执行此按位异或?它用于网络编码的东西。

4

1 回答 1

2

如果要对字符串中的每个字符进行异或运算,只需遍历字符串并创建一个新字符:

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;
}
于 2013-09-16T14:41:04.320 回答