NFRCR
NFRCR

Reputation: 5570

Boost.Multiprecision cpp_int - convert into an array of bytes?

http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/index.html

I just started exploring this library. There doesn't seem to be a way to convert cpp_int into an array of bytes.

Can someone see such functionality?

Upvotes: 7

Views: 3791

Answers (2)

lubgr
lubgr

Reputation: 38267

This is the documented way of exporting and importing the underlying limb data of a cpp_int (and cpp_float). From the example given in the docs, trimmed down for the specific question:

#include <boost/multiprecision/cpp_int.hpp>
#include <vector>

using boost::multiprecision::cpp_int;

cpp_int i{"2837498273489289734982739482398426938568923658926938478923748"};

// export into 8-bit unsigned values, most significant bit first:
std::vector<unsigned char> bytes;

export_bits(i, std::back_inserter(bytes), 8);

This mechanism is quite flexible, as you can save the bytes into other integral types (just remember to specify the number of bits per array element), which in turn works with import_bits, too, if you need to restore a cpp_int from the deserialized sequence.

Upvotes: 2

Akira Takahashi
Akira Takahashi

Reputation: 3012

This is undocument way. cpp_int's backend have limbs() member function. This function return internal byte array value.

#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>

namespace mp = boost::multiprecision;

int main()
{
    mp::cpp_int x("11111111112222222222333333333344444444445555555555");

    std::size_t size = x.backend().size();
    mp::limb_type* p = x.backend().limbs();

    for (std::size_t i = 0; i < size; ++i) {
        std::cout << *p << std::endl;
        ++p;
    }
}

result:

10517083452262317283
8115000988553056298
32652620859

Upvotes: 2

Related Questions