我该如何XOR这两个向量的内容

How can I xor the content of these two vectors?

本文关键字:两个 向量 XOR      更新时间:2023-10-16

我有两个无符号字符的向量:

std::vector<uint8_t> a = {'xac', 'xf9', 'xe1', 'o', 'R', '5', 'M', 'x9b', 'x13', 'I', '2', '%', 'W', ',', 'xd0', 't', 'xde', 'x94', 'xb3', '+'};

std::vector<uint8_t> b =  {'7','x8e',';','xca','xc6','xc7','B','b','x','z','x89','i','P','xa3','%','x86','xdb','^','xdb','x9f'};

我如何x x词的内容?我可以将它们施放到int

我建议您使用 std::valarray<T>而不是 std::vector<T>为此,它已经以元素的方式定义了所有位和算术运算符。

那么您的数据将是

#include <valarray>
std::valarray<uint8_t> a = { 0xacu, 0xf9u, 0xe1u, 'o', 'R', '5', 'M', 0x9bu, 0x13u, 'I', '2', '%', 'W', ',', 0xd0u, 't', 0xdeu, 0x94u, 0b3u, '+'};
std::valarray<uint8_t> b =  {'7', 0x8eu, ';', 0xcau, 0xc6u, 0xc7u, 'B', 'b', 'x', 'z', 0x89u, 'i', 'P', 0xa3u, '%', 0x86u, 0xdbu, '^', 0xdbu, 0x9fu};

和xor将简单地

auto c = a ^ b;

我假设您的向量的大小相等(如果我理解您打算正确地做的事情(

非常容易:

// Xor every couple of elements and store results in `a`
std::transform(a.begin(), a.end(), b.begin(),
    a.begin(), std::bit_xor<uint8_t>()); // std::bit_xor defined in <functional>

(等效于(

std::transform(a.begin(), a.end(), b.begin(),
    a.begin(), [](auto e1, auto e2) {
    return e1 ^ e2;
});

实时示例

ben的std :: valarray建议是另一种很好的方法。

我如何x x词?

向量的每个元素都是积分类型。您可以使用:

uint8_t res = a[i] ^ b[i];

我可以将它们施放到int吗?

您可以,但没有必要。所有积分类型都可以用作^操作员的操作数。

我如何x x词?

您可以使用以下算法:

let c be a new vector of same size as a and b
for i in [0 .. a.size()[
    c[i] = a[i]^b[i]

提升zip迭代器可以提供帮助:

#include <iostream>
#include <iomanip>
#include <vector>
#include <boost/iterator/zip_iterator.hpp>
void show(std::vector<uint8_t>const& result);
std::vector<uint8_t> a = {'xac', 'xf9', 'xe1', 'o', 'R', '5', 'M', 'x9b', 'x13', 'I', '2', '%', 'W', ',', 'xd0',
                          't', 'xde', 'x94', 'xb3', '+'};
std::vector<uint8_t> b = {'7', 'x8e', ';', 'xca', 'xc6', 'xc7', 'B', 'b', 'x', 'z', 'x89', 'i', 'P', 'xa3', '%',
                          'x86', 'xdb', '^', 'xdb', 'x9f'};
int main() {
    std::vector<uint8_t> result;
    auto Xor = [](auto const& xy) { return boost::get<0>(xy) ^ boost::get<1>(xy); };
    auto first = boost::make_zip_iterator(boost::make_tuple(a.begin(), b.begin()));
    auto last = boost::make_zip_iterator(boost::make_tuple(a.end(), b.end()));
    std::transform(first, last,
                   std::back_inserter(result),
                   Xor);
    show(result);
}
void show(std::vector<uint8_t>const& result)
{
    const char *sep = "";
    for (uint8_t n : result) {
        std::cout << sep << std::hex << std::setw(2) << std::setfill('0') << std::uint32_t(n);
        sep = ", ";
    }
    std::cout << std::endl;
}