gpt4 book ai didi

c++ - 将 boost::multiprecision 数据类型写入二进制文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:50:25 35 4
gpt4 key购买 nike

我使用 boost::multiprecision::uint128_t 类型来对 128 位值执行按位运算。但是,我无法将 128 位值写入二进制文件。特别是需要用零填充值。

例如,如果 uint128_t 值为 0x123456 然后在十六进制编辑器中查看文件,我想要序列:

56 34 12 00 00 00 00 00 00 00 00 00 00 00 00 00

#include <boost/multiprecision/cpp_int.hpp>
#include <fstream>

boost::multiprecision::uint128_t temp = 0x123456;
std::ofstream ofile("test.bin", std::ios::binary);
ofile.write((char*)&temp, 16);
ofile.close();

相反,二进制文件以一个值结束:

56 34 12 00 CC CC CC CC CC CC CC CC CC

我可以看到 uint128_t 模板的 boost 后端似乎将 128 位存储为四个 32 位值。并且有一个“肢体”值,表示正在使用多少个 32 位值。当 32 位值未使用时,它们将填充为 0xCCCCCCCC。所以 ofstream.write 遍历字符数组并写出 0xC

boost 库中是否缺少某些有助于正确写出的东西,或者我是否需要将 uint128_t 值转换为另一种数据类型?

最佳答案

我深入研究了它,您可以编写一个实用程序将连续的肢体写入 POD 对象:

Live On Coliru

#include <boost/multiprecision/cpp_int.hpp>
#include <fstream>

template <typename BigInt, typename Backend = typename BigInt::backend_type>
void write_binary(std::ostream& os, BigInt const& number) {
static_assert(boost::is_pod<typename Backend::local_limb_type>::value, "not allowed");

os.write(
reinterpret_cast<char const*>(number.backend().limbs()),
number.backend().size()*sizeof(typename Backend::local_limb_type)
);
}

int main()
{
using uint128_t = boost::multiprecision::uint128_t;

std::ofstream ofs("binary.dat", std::ios::binary);
write_binary(ofs, uint128_t(42));
}

十六进制转储:

0000000: 2a00 0000 0000 0000 0000 0000 0000 0000  *...............

恐怕这不是可移植的(它可能取决于 128 位数字的编译器内部函数的可用性)。至少它是类型安全的。

关于c++ - 将 boost::multiprecision 数据类型写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30090325/

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