1 #ifndef BIGINTEGERUTILS_H
2 #define BIGINTEGERUTILS_H
4 #include "BigInteger.hh"
9 * - Convenient std::string <-> BigUnsigned/BigInteger conversion routines
10 * - std::ostream << operators for BigUnsigned/BigInteger */
12 // std::string conversion routines. Base 10 only.
13 std::string bigUnsignedToString(const BigUnsigned &x);
14 std::string bigIntegerToString(const BigInteger &x);
15 BigUnsigned stringToBigUnsigned(const std::string &s);
16 BigInteger stringToBigInteger(const std::string &s);
18 // Creates a BigInteger from data such as `char's; read below for details.
20 BigInteger dataToBigInteger(const T* data, BigInteger::Index length, BigInteger::Sign sign);
22 // Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
23 std::ostream &operator <<(std::ostream &os, const BigUnsigned &x);
25 // Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
26 // My somewhat arbitrary policy: a negative sign comes before a base indicator (like -0xFF).
27 std::ostream &operator <<(std::ostream &os, const BigInteger &x);
29 // BEGIN TEMPLATE DEFINITIONS.
32 * Converts binary data to a BigInteger.
33 * Pass an array `data', its length, and the desired sign.
35 * Elements of `data' may be of any type `T' that has the following
36 * two properties (this includes almost all integral types):
38 * (1) `sizeof(T)' correctly gives the amount of binary data in one
39 * value of `T' and is a factor of `sizeof(Blk)'.
41 * (2) When a value of `T' is casted to a `Blk', the low bytes of
42 * the result contain the desired binary data.
45 BigInteger dataToBigInteger(const T* data, BigInteger::Index length, BigInteger::Sign sign) {
46 // really ceiling(numBytes / sizeof(BigInteger::Blk))
47 unsigned int pieceSizeInBits = 8 * sizeof(T);
48 unsigned int piecesPerBlock = sizeof(BigInteger::Blk) / sizeof(T);
49 unsigned int numBlocks = (length + piecesPerBlock - 1) / piecesPerBlock;
51 // Allocate our block array
52 BigInteger::Blk *blocks = new BigInteger::Blk[numBlocks];
54 BigInteger::Index blockNum, pieceNum, pieceNumHere;
57 for (blockNum = 0, pieceNum = 0; blockNum < numBlocks; blockNum++) {
58 BigInteger::Blk curBlock = 0;
59 for (pieceNumHere = 0; pieceNumHere < piecesPerBlock && pieceNum < length;
60 pieceNumHere++, pieceNum++)
61 curBlock |= (BigInteger::Blk(data[pieceNum]) << (pieceSizeInBits * pieceNumHere));
62 blocks[blockNum] = curBlock;
65 // Create the BigInteger.
66 BigInteger x(blocks, numBlocks, sign);