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

标签 c++ boost ofstream multiprecision

我使用 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/

相关文章:

visual-studio-2010 - fatal error LNK1104 : cannot open file 'libboost_date_time-vc100-mt-gd-1_53.lib' - file ignored, 无论我链接什么

c++ - "Function"不是 C++ 类型

c++ - 在 JSON 字符串中序列化 utf-8 字符的标准方法

c++ - 从 Apache 正在运行的 C++ 代码调用 bash 脚本的权限问题

c++ - 使用自定义编译的 zlib 在 Linux 上编译 Boost.Iostream 会导致多个卡纸错误

c++ - 我无法让非常基本的命令提示 rune 本处理器正常工作。 ofstream() 的问题

c++ - 使用 Eclipse 时如何向我的 C++ 编译可执行文件添加图标?

c++ - 将 boost::shared_ptr 初始化为 NULL

c++为什么变量 "file"在我声明时未声明?

c++ - 为什么我可以有一个 std::vector<std::ofstream*> 但不能有一个 std::vector<std::ofstream> ?