Search code examples
c++boostmultiprecision

boost mpz_int with base other than 2, 8, 10, 16


I can create multi precision integers from a string with standard base

#include <boost/multiprecision/gmp.hpp>
...
using namespace boost::multiprecision;
mpz_int decimal("10");
mpz_int hexadecimal("0xa");
mpz_int octal("012");
mpz_int binary("0b1010");

to use base 2 to 62 like in GMP, one can use for example

#include <gmp.h>
...
mpz_t auxiliary;
mpz_init(auxiliary);
mpz_set_str(auxiliary,"11",9);
mpz_int j = auxiliary;
mpz_clear(auxiliary);

Is there a more direct approach with no auxiliary variable ?


Solution

  • Yes.

    #include <iostream>
    #include <boost/multiprecision/gmp.hpp>
    
    int main()
    {
      boost::multiprecision::mpz_int j;
      mpz_set_str( j.backend().data(), "11", 9 );
      std::cout << j << "\n";
    }
    

    Be careful to read the docs.