如何序列化GMP有理数? [英] How to serialize a GMP rational number?

查看:224
本文介绍了如何序列化GMP有理数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法以二进制形式序列化GMP有理数?我只看到读取/写入 FILE 的函数,但即使有一个文本形式。我可以转换为分子/分母,并使用整数函数,但同样只有一个 FILE 输出可用。

Is there a way to serialize a GMP rational number in binary form? I only see functions for reading/writing to a FILE, but even there it is a text form. I could convert to numerator/denominator and use the integer functions, but again there only a FILE output is available. I need to be able to get the raw bytes or write to a C++ stream.

推荐答案

使用 mpz_export mpz_import 功能(感谢Marc指出),我想出了下面的代码。这是包含 mpz_class 值的数字类的一部分。

Using the mpz_export and mpz_import function (thanks to Marc for pointing that out), I came up with the below code. This is part of a number class that contains a mpz_class value.

这真的表明GMP没有适当的导入/导出功能。下面是比使用一个特性更好的解决方法。

This really shows that GMP doesn't have a proper import/export functionality. The below is more of a workaround than use of a feature.

void number::write( std::ostream & out ) const {
    int8_t neg = value.get_num() < 0;
    out.write( (char*)&neg, sizeof(neg) );

    size_t c;
    void * raw = mpz_export( nullptr, &c, 1, 1, 0, 0, value.get_num().get_mpz_t() );
    out.write( (char*)&c, sizeof(c) );
    out.write( (char*)raw, c );
    free(raw);

    raw = mpz_export( nullptr, &c, 1, 1, 0, 0, value.get_den().get_mpz_t() );
    out.write( (char*)&c, sizeof(c) );
    out.write( (char*)raw, c );
    free(raw);
}

void number::read( std::istream & in ) {
    mpz_class num, den;
    size_t s;
    std::vector<uint8_t> v;

    int8_t neg;
    in.read( (char*)&neg, sizeof(neg) );

    in.read( (char*)&s, sizeof(s) );
    v.resize(s);
    in.read( (char*)&v[0], s );
    mpz_import( num.get_mpz_t(), s, 1, 1, 0, 0, &v[0] );

    in.read( (char*)&s, sizeof(s) );
    v.resize(s);
    in.read( (char*)&v[0], s );
    mpz_import( den.get_mpz_t(), s, 1, 1, 0, 0, &v[0] );

    value = mpq_class(num) / mpq_class(den);
    if( neg ) {
        value = -value;
    }
}

这篇关于如何序列化GMP有理数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆