Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 341
NFRCR Avatar asked Mar 30 '13 16:03

NFRCR


2 Answers

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
like image 187
Akira Takahashi Avatar answered Oct 12 '22 13:10

Akira Takahashi


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.

like image 37
lubgr Avatar answered Oct 12 '22 14:10

lubgr