Integer formatted output

Integer formatted output#

Preliminaries#

Let us load the mp++ runtime, include the headers and import the user-defined literals:

#pragma cling add_include_path("$CONDA_PREFIX/include")
#pragma cling add_library_path("$CONDA_PREFIX/lib")
#pragma cling load("mp++")

#include <mp++/integer.hpp>
#include <mp++/exceptions.hpp>

using namespace mppp::literals;
using int_t = mppp::integer<1>;

Let us also include a few useful bits from the standard library:

#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>

String conversions#

Multiprecision integers can be converted to string via the to_string() member function. By default, a base-10 representation is produced:

std::cout << (1123_z1).to_string();
1123

But bases from 2 to 62 are supported as well:

std::cout << (1123_z1).to_string(2);
10001100011
std::cout << (1123_z1).to_string(16);
463
std::cout << (1123_z1).to_string(45);
Oh
std::cout << (1123_z1).to_string(62);
I7

The string representations are always exact - that is, it is always possible to re-convert the string back to the original value exactly:

int_t{(1123_z1).to_string()}
1123
int_t{(1123_z1).to_string(2), 2}
1123
int_t{(1123_z1).to_string(45), 45}
1123

Formatted stream output#

Multiprecision integers will respect the format flags in output streams:

{
    std::ostringstream oss;
    oss << "Default format: " << 123456_z1;
    std::cout << oss.str();
}
Default format: 123456

Different bases:

{
    std::ostringstream oss;
    oss << "Base 16            : " << std::setbase(16) << 123456_z1 << '\n';
    oss << "Base  8            : " << std::setbase(8) << 123456_z1 << '\n';
    oss << "Base 16 with prefix: " << std::showbase << std::setbase(16) << 123456_z1 << '\n';
    oss << "Base  8 with prefix: " << std::setbase(8) << 123456_z1 << '\n';
    oss << "Base 16 uppercase  : " << std::showbase << std::uppercase << std::setbase(16) << 123456_z1 << '\n';
    std::cout << oss.str();
}
Base 16            : 1e240
Base  8            : 361100
Base 16 with prefix: 0x1e240
Base  8 with prefix: 0361100
Base 16 uppercase  : 0X1E240

Other formatting options:

{
    std::ostringstream oss;
    oss << "Force '+' sign    : " << std::showpos << 123456_z1 << '\n';
    oss << "Field witdh       : " << std::noshowpos << std::setw(20) << 123456_z1 << '\n';
    oss << "Fill characters   : " << std::setw(20) << std::setfill('*') << 123456_z1 << '\n';
    oss << "Align left        : " << std::setw(20) << std::setfill('*') << std::left << 123456_z1 << '\n';
    oss << "Internal alignment: " << std::setw(20) << std::setfill('*') << std::internal << -123456_z1 << '\n';
    std::cout << oss.str();
}
Force '+' sign    : +123456
Field witdh       :               123456
Fill characters   : **************123456
Align left        : 123456**************
Internal alignment: -*************123456