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