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