我该如何XOR这两个向量的内容
How can I xor the content of these two vectors?
我有两个无符号字符的向量:
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;
}
相关文章:
- 在C++中查找两个向量之间最相似的值
- 如何在C++中从两个向量生成所有可能的对?
- 返回两个向量 – 使用引用还是元组?
- 检查两个向量是否并行的最有效方法
- 如何获得比较两个向量对的子集
- 如何在 c++ 中对两个向量进行线性搜索?
- 如何在 c++ 中从两个向量创建 JSON 对象?
- C++如何同时删除位于两个向量中的 2 个指针?
- 如何通过 stl 容器和算法库计算两个向量的内积?
- 删除两个向量中的重复项
- 两个向量在犰狳中相等?
- 为什么我无法比较自定义类类型的两个向量?
- 通过块比较两个向量时,如何避免重复
- Boost.Test - 如何在交叉点上检查两个向量
- 通过移动从两个向量创建元组向量
- 如何在C 中合并两个向量
- R- armadillo c :用其他两个向量对向量进行排序
- 使用嵌套循环搜索两个向量并查看其属性
- 如何以精度换取速度来评估C++中两个向量的点积符号?(不特定于硬件)
- 我该如何XOR这两个向量的内容