gpt4 book ai didi

c++ - 如何将 boost::multiprecision::cpp_int 转换为字节数组

转载 作者:行者123 更新时间:2023-11-30 03:23:17 26 4
gpt4 key购买 nike

我需要两个函数:

std::vector<uint8_t> bigint_to_bytes(cpp_int a); 

cpp_int bytes_to_bigint(std::vector<uint8_t> const& a);

google了一下,发现bigint_to_bytes可以通过backend().limbs()来实现,不知道如何实现bytes_to_bigint

如何通过一个字节数组构造一个cpp_int

最佳答案

我建议采用简单的方法并使用内置的后端序列化:

Bytes to_bytes(Bigint const& i) {
namespace io = boost::iostreams;
namespace ba = boost::archive;

std::vector<char> chars;
{
io::stream_buffer<io::back_insert_device<Chars> > bb(chars);
ba::binary_oarchive oa(bb, ba::no_header | ba::no_tracking | ba::no_codecvt);
oa << i;
}

return {chars.begin(), chars.end()};
}

那么反过来就是

Bigint to_bigint(Bytes const& v) {
namespace io = boost::iostreams;
namespace ba = boost::archive;

Bigint i;
{
std::vector<char> chars { v.begin(), v.end() };
io::stream_buffer<io::array_source> bb(chars.data(), chars.size());
ba::binary_iarchive ia(bb, ba::no_header | ba::no_tracking | ba::no_codecvt);
ia >> i;
}
return i;
}

这里唯一的“遗憾”是 Boost 二进制存档不支持具有 char_type uint8_t 的流这意味着您无法复制。

你可以通过引入一些丑陋的 reinterpret_casts 来解决这个问题(并且需要限制有效的序列化大小)。我将把它作为众所周知的练习留给读者。¹

演示

Live On Coliru

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_int/serialize.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

#include <iostream>

namespace {
using Bigint = boost::multiprecision::cpp_int;
using Chars = std::vector<char>;
using Bytes = std::vector<uint8_t>;

Bytes to_bytes(Bigint const& i) {
namespace io = boost::iostreams;
namespace ba = boost::archive;

std::vector<char> chars;
{
io::stream_buffer<io::back_insert_device<Chars> > bb(chars);
ba::binary_oarchive oa(bb, ba::no_header | ba::no_tracking | ba::no_codecvt);
oa << i;
}

return {chars.begin(), chars.end()};
}

Bigint to_bigint(Bytes const& v) {
namespace io = boost::iostreams;
namespace ba = boost::archive;

Bigint i;
{
std::vector<char> chars { v.begin(), v.end() };
io::stream_buffer<io::array_source> bb(chars.data(), chars.size());
ba::binary_iarchive ia(bb, ba::no_header | ba::no_tracking | ba::no_codecvt);
ia >> i;
}
return i;
}
}

int main() {
Bigint i = 77;
i <<= 33;

return i == to_bigint(to_bytes(i))? 0 : 1;
}

退出代码为 0。

¹ 反过来更容易:更改为 vector<int8_t>相反:http://coliru.stacked-crooked.com/a/3dbff52c2daab58e

关于c++ - 如何将 boost::multiprecision::cpp_int 转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50465041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com