1

I'm new to Boost and trying to use its multi-precision library to multiply very large inputs:

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;

I need to be able to save the result as a string in binary form. I have tried to access the number of "limbs" in the integer:

int limbs = my_1024_bit_result.backend.limbs();

and then iterate through each limb and use the bitset function to convert each limb to a binary string, but it did not work.

How else could I achieve this?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Spiegs
  • 11
  • 1
  • I believe you're overthinking this. Pretend you'e not using the multi-precision library -- how would you generate the string? Wouldn't it be the very same code, except the `int` type would be replaced with `cpp_int`? – PaulMcKenzie Apr 26 '20 at 03:39
  • side remark: are you sure your first 2 lines work properly for numbers with > 64 bits? – Marc Glisse Apr 26 '20 at 09:16
  • @MarcGlisse I suppose they should be string initialized indeed, but the `0b` format is not support by their constructor – sehe Apr 26 '20 at 16:07

1 Answers1

1

If you actually meant binary digits:

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";
}

Prints

78922901 * 726187641175 = 57312835311878048675

0b100101101000100010010010101 * 0b1010100100010100001010000000100101010111 = 0b110001101101100000000110000000111101001010111101001000101110100011

Serialization?

In case you meant "binary serialization", use serialization:

sehe
  • 374,641
  • 47
  • 450
  • 633