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