3ac75dc0163f8a510c7cb4ec70ed2a04a6d8e50c
[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.getMagnitude()))
17                 : (easyBUtoString(x.getMagnitude()));
18 }
19
20 BigUnsigned easyStringToBU(const std::string &s) {
21         return BigUnsigned(BigUnsignedInABase(s, 10));
22 }
23
24 BigInteger 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'.
31 std::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).
52 std::ostream &operator <<(std::ostream &os, const BigInteger &x) {
53         if (x.getSign() == BigInteger::negative)
54                 os << '-';
55         os << x.getMagnitude();
56         return os;
57 }