我如何xor这两个向量的内容?

时间:2017-04-21 15:40:12

标签: c++ bit-manipulation

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

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'};

我如何xor这些载体的内容?我可以将它们转换为int吗?

5 个答案:

答案 0 :(得分:4)

我建议您使用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;

答案 1 :(得分:3)

我假设你的矢量大小相等(如果我明白你打算做什么)

非常简单:

// 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;
});

Live Example

Ben's std::valarray建议是另一种很好的方式。

答案 2 :(得分:2)

  

我怎样才能对这些载体的内容进行xor?

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

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

我可以将它们转换为int吗?

你可以,但没有必要。所有整数类型都可以用作^运算符的操作数。

答案 3 :(得分:0)

  

我怎样才能对这些载体的内容进行xor?

您可以使用以下算法:

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]

答案 4 :(得分:0)

boost 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;
}