1 #ifndef BIGINTEGERUTILS_H
2 #define BIGINTEGERUTILS_H
4 #include "BigInteger.hh"
10 * (1) `std::string <=> BigUnsigned/BigInteger' conversion routines easier than `BigUnsignedInABase'
11 * (2) << and >> operators for BigUnsigned/BigInteger, std::istream/std::ostream
14 // Conversion routines. Base 10 only.
15 std::string easyBUtoString(const BigUnsigned &x);
16 std::string easyBItoString(const BigInteger &x);
17 BigUnsigned easyStringToBU(const std::string &s);
18 BigInteger easyStringToBI(const std::string &s);
20 // Creates a BigInteger from data such as `char's; read below for details.
22 BigInteger easyDataToBI(const T* data, BigInteger::Index length, BigInteger::Sign sign);
24 // Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
25 std::ostream &operator <<(std::ostream &os, const BigUnsigned &x);
27 // Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
28 // My somewhat arbitrary policy: a negative sign comes before a base indicator (like -0xFF).
29 std::ostream &operator <<(std::ostream &os, const BigInteger &x);
32 * =================================
33 * BELOW THIS POINT are template definitions; above are declarations. See `NumberlikeArray.hh'.
37 * Converts binary data to a BigInteger.
38 * Pass an array `data', its length, and the desired sign.
40 * Elements of `data' may be of any type `T' that has the following
41 * two properties (this includes almost all integral types):
43 * (1) `sizeof(T)' correctly gives the amount of binary data in one
44 * value of `T' and is a factor of `sizeof(Blk)'.
46 * (2) When a value of `T' is casted to a `Blk', the low bytes of
47 * the result contain the desired binary data.
50 BigInteger easyDataToBI(const T* data, BigInteger::Index length, BigInteger::Sign sign) {
51 // really ceiling(numBytes / sizeof(BigInteger::Blk))
52 unsigned int pieceSizeInBits = 8 * sizeof(T);
53 unsigned int piecesPerBlock = sizeof(BigInteger::Blk) / sizeof(T);
54 unsigned int numBlocks = (length + piecesPerBlock - 1) / piecesPerBlock;
56 // Allocate our block array
57 BigInteger::Blk *blocks = new BigInteger::Blk[numBlocks];
59 BigInteger::Index blockNum, pieceNum, pieceNumHere;
62 for (blockNum = 0, pieceNum = 0; blockNum < numBlocks; blockNum++) {
63 BigInteger::Blk curBlock = 0;
64 for (pieceNumHere = 0; pieceNumHere < piecesPerBlock && pieceNum < length;
65 pieceNumHere++, pieceNum++)
66 curBlock |= (BigInteger::Blk(data[pieceNum]) << (pieceSizeInBits * pieceNumHere));
67 blocks[blockNum] = curBlock;
70 // Create the BigInteger.
71 BigInteger x(blocks, numBlocks, sign);