c++ - 如何以二进制形式显示C++ Boost Library的多精度大整数?

标签 c++ boost boost-multiprecision

我是Boost的新手,并尝试使用其多精度库来增加非常大的输入:

mp::uint1024_t my_1024_bit_int1 = 0b00100101101000100010010...010101;
mp::uint1024_t my_1024_bit_int2 = 0b0010101001000101000010100000001001...01010111; // bigger in practice
mp::uint1024_t my_1024_bit_result = my_1024_bit_int2*my_1024_bit_int1;

我需要能够将结果另存为二进制形式的字符串。我试图访问整数中的“肢体”数:
int limbs = my_1024_bit_result.backend.limbs();

然后遍历每个肢体,并使用bitset函数将每个肢体转换为二进制字符串,但是它不起作用。

我还能怎么实现呢?

最佳答案

如果您实际上是指二进制数字:

template <typename Integer>
std::string to_bin(Integer num) {
    auto sign = num.sign();
    num = abs(num);

    std::string result;
    while (num) {
        result += "01"[int(num % 2)];
        num /= 2;
    }
    result += sign<0? "b0-": "b0";
    std::reverse(begin(result), end(result));
    return result;
}

Note how it supports signed types as well



Live On Coliru
int main() {
    mp::uint1024_t a=0b00100101101000100010010010101;
    mp::uint1024_t b=0b001010100100010100001010000000100101010111; // bigger in practice
    mp::uint1024_t c = a * b;

    std::cout << a << " * " << b << " = " << c << "\n";
    std::cout << "\n" << to_bin(a) << " * " << to_bin(b) << "\n = " << to_bin(c) << "\n";
}

版画

78922901 * 726187641175 = 57312835311878048675

0b100101101000100010010010101 * 0b1010100100010100001010000000000000100101010111
= 0b110001101101100000000110000000111101001010111101001000101110100011

序列化?

如果您的意思是“二进制序列化”,请使用序列化:
  • Writing boost::multiprecision data type to binary file
  • 关于c++ - 如何以二进制形式显示C++ Boost Library的多精度大整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61435470/

    相关文章:

    java - 通过删除 PRIME ASCII 字符来打印字符串

    c++ - 切换到 Linux 进行 Windows 开发,坏主意?

    c++ - 将 boost::multi precision::mpq_rational 舍入到最接近的整数

    c++ - 是否可以为 boost::random::uniform_int_distribution<> 设置确定性种子?

    c++ - 使用 cpp_int 构建一个大的 boost unordered_map

    c++ - 在 Crypto++ 中使用 RSA 加密对称 AES key

    C++ 不允许不完整类型

    python - 你如何在 boost::python 中使用 "from __future__ import division"?

    c++ - Boost MPL 占位符和 Lambda

    c++ - Boost::多精度和cardinal_cubic_b_spline