2

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

例如,如果该uint128_t0x123456在十六进制编辑器中查看文件,我将需要以下序列:

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's。

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

4

1 回答 1

0

我深入研究了它,您可以编写一个实用程序来将连续的肢体写入 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 位数字的编译器内在函数的可用性)。至少它是类型安全的。

于 2015-05-07T01:35:25.933 回答