Massive cleanup of the entire codebase. Notable changes include:
[bigint/bigint.git] / BigIntegerUtils.cc
CommitLineData
05780f4b
MM
1#include "BigIntegerUtils.hh"
2#include "BigUnsignedInABase.hh"
3
4/*
6e1e0f2f
MM
5 * This file includes:
6 * (1) `std::string <=> BigUnsigned/BigInteger' conversion routines easier than `BigUnsignedInABase'
7 * (2) << and >> operators for BigUnsigned/BigInteger, std::istream/std::ostream
8 */
05780f4b
MM
9
10std::string easyBUtoString(const BigUnsigned &x) {
11 return std::string(BigUnsignedInABase(x, 10));
12}
13
14std::string easyBItoString(const BigInteger &x) {
3e132790
MM
15 return (x.getSign() == BigInteger::negative)
16 ? (std::string("-") + easyBUtoString(x.getMagnitude()))
17 : (easyBUtoString(x.getMagnitude()));
05780f4b
MM
18}
19
20BigUnsigned easyStringToBU(const std::string &s) {
21 return BigUnsigned(BigUnsignedInABase(s, 10));
22}
23
24BigInteger easyStringToBI(const std::string &s) {
25 return (s[0] == '-') ?
26 BigInteger(easyStringToBU(s.substr(1, s.length() - 1)), BigInteger::negative) :
27 BigInteger(easyStringToBU(s));
28}
29
30// Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
31std::ostream &operator <<(std::ostream &os, const BigUnsigned &x) {
32 BigUnsignedInABase::Base base;
33 long osFlags = os.flags();
34 if (osFlags & os.dec)
35 base = 10;
36 else if (osFlags & os.hex) {
37 base = 16;
38 if (osFlags & os.showbase)
39 os << "0x";
40 } else if (osFlags & os.oct) {
41 base = 8;
42 if (osFlags & os.showbase)
43 os << '0';
44 } else
45 throw "std::ostream << BigUnsigned: Could not determine the desired base from output-stream flags";
46 std::string s = std::string(BigUnsignedInABase(x, base));
47 os << s;
48 return os;
49}
50// Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
51// My somewhat arbitrary policy: a negative sign comes before a base indicator (like -0xFF).
52std::ostream &operator <<(std::ostream &os, const BigInteger &x) {
53 if (x.getSign() == BigInteger::negative)
54 os << '-';
3e132790 55 os << x.getMagnitude();
05780f4b
MM
56 return os;
57}