【发布时间】:2015-05-07 09:35:25
【问题描述】:
我使用 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 CC CC
我可以看到 uint128_t 模板的 boost 后端似乎将 128 位存储为四个 32 位值。并且有一个“肢体”值,它指示有多少个 32 位值正在使用中。当 32 位值未使用时,它们将填充为 0xCCCCCCCC。所以ofstream.write 正在遍历字符数组并写出0xC。
我在 boost 库中是否缺少一些东西来帮助正确地写出来,还是我需要将 uint128_t 值转换为其他数据类型?
【问题讨论】:
-
(char*)reinterpret_cast 是 evil 并且(显然)不起作用。请参阅有关如何使用 boost 序列化进行序列化的相关答案:stackoverflow.com/a/28705686/85371
标签: c++ boost ofstream multiprecision