将boost :: multiprecision数据类型写入二进制文件 [英] Writing boost::multiprecision data type to binary file
问题描述
我正在使用 boost :: multiprecision :: uint128_t
类型以便对128位值执行按位运算.但是我在将128位值写到二进制文件时遇到了麻烦.特别是需要用零填充值.
I was using the boost::multiprecision::uint128_t
type in order to perform bitwise operations on a 128 bit value. However I am having trouble writing the 128 bit value out to a binary file. Specifically with the need to pad out the value with zeros.
作为一个示例,如果 uint128_t
的值为 0x123456
,则在十六进制编辑器中查看文件,我需要以下顺序:
As an example if the uint128_t
value was 0x123456
then looking at the file in the hex editor I would want the sequence:
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();
相反,二进制文件以一个值结尾:
Instead the binary file ends up with a value:
56 34 12 00 CC CC CC CC CC CC CC CC CC CC CC CC CC
我可以看到 uint128_t
模板的boost后端似乎将128位存储为四个32位值.并具有"limb"值,该值指示正在使用多少个32位值.当不使用32位值时,它们将用 0xCCCCCCCC
填充.因此, ofstream.write
正在遍历字符数组并写出 0xC
.
I can see the the boost backend for the uint128_t
template appears to store the 128 bits as four 32 bit values. And has a "limb" value which indicates how many 32 bit values are in use. When the 32 bit values are not in use they are filled with 0xCCCCCCCC
. So the ofstream.write
is walking through the array of characters and writing out the 0xC
's.
boost库中是否缺少某些内容来帮助正确地将其写出,还是需要将 uint128_t
值转换为其他数据类型?
Is there something I am missing in the boost library to help write this out correctly, or will I need to convert the uint128_t
value into some another data type?
推荐答案
我深入其中,可以编写一个实用程序将连续的肢体作为POD对象:
I dived into it, you can write a utility to write the contiguous limbs as POD objects:
#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));
}
Hexdump:
0000000: 2a00 0000 0000 0000 0000 0000 0000 0000 *...............
恐怕这不是可移植的(它可能取决于128位数字的编译器内在函数的可用性).至少它是安全类型.
I'm afraid this isn't portable (it may depend on the availability of compiler intrinsics for 128 bit numbers). At least it's type safe.
这篇关于将boost :: multiprecision数据类型写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!