Commit | Line | Data |
---|---|---|
e67d6049 MM |
1 | /* |
2 | * Big Integer Library | |
3 | * Filename: BigIntegerIO.h | |
4 | * Author: Matt McCutchen | |
5 | * Version: 2004.1205 | |
6 | */ | |
7 | ||
8 | #include "BigIntegerIO.h" | |
9 | ||
10 | std::ostream& operator<<(std::ostream &os, BigUnsigned x) { | |
11 | if (x.getLength() == 0) | |
12 | os << '0'; | |
13 | else { | |
14 | BigUnsigned ten(10); | |
15 | ||
16 | /* | |
17 | * This buffer is filled with the decimal digits of x. | |
18 | * sizeof(BigUnsigned::Blk) * x.getLength() is an upper bound on the | |
19 | * number of bytes in x, and a byte takes at most 3 decimal | |
20 | * digits, so this is a convenient upper bound. | |
21 | */ | |
22 | char *buf = new char[sizeof(BigUnsigned::Blk) * x.getLength() * 3]; | |
23 | //std::cout << "bufferlength" << sizeof(BigUnsigned::Blk) * x.getLength() * 3<< std::endl; | |
24 | int bufPos = 0; // first unfilled position | |
25 | ||
26 | // While x is not zero... | |
27 | while (!x.isZero()) { | |
28 | //std::cout << "bufPos=" << bufPos << std::endl; | |
29 | // Get next digit | |
30 | buf[bufPos] = char(int(x % ten) + '0'); | |
31 | // Remove it from x | |
32 | x /= ten; | |
33 | // Next buffer slot | |
34 | bufPos++; | |
35 | } | |
36 | ||
37 | // Now print the digits to os. | |
38 | while (bufPos > 0) { | |
39 | bufPos--; | |
40 | os << buf[bufPos]; | |
41 | } | |
42 | ||
43 | // Free the buffer and return the stream (as customary) | |
44 | delete buf; | |
45 | return os; | |
46 | } | |
47 | } | |
48 | ||
49 | std::ostream& operator<<(std::ostream &os, BigInteger x) { | |
50 | switch (x.getSign()) { | |
51 | case BigInteger::positive: | |
52 | os << BigUnsigned(x); | |
53 | break; | |
54 | case BigInteger::zero: | |
55 | os << '0'; | |
56 | break; | |
57 | case BigInteger::negative: | |
58 | os << '-' << BigUnsigned(x); | |
59 | break; | |
60 | } | |
61 | return os; | |
62 | } |