Massive cleanup of the entire codebase. Notable changes include:
[bigint/bigint.git] / BigIntegerUtils.hh
... / ...
CommitLineData
1#ifndef BIGINTEGERUTILS_H
2#define BIGINTEGERUTILS_H
3
4#include "BigInteger.hh"
5#include <string>
6#include <iostream>
7
8/*
9 * This file includes:
10 * (1) `std::string <=> BigUnsigned/BigInteger' conversion routines easier than `BigUnsignedInABase'
11 * (2) << and >> operators for BigUnsigned/BigInteger, std::istream/std::ostream
12 */
13
14// Conversion routines. Base 10 only.
15std::string easyBUtoString(const BigUnsigned &x);
16std::string easyBItoString(const BigInteger &x);
17BigUnsigned easyStringToBU(const std::string &s);
18BigInteger easyStringToBI(const std::string &s);
19
20// Creates a BigInteger from data such as `char's; read below for details.
21template <class T>
22BigInteger easyDataToBI(const T* data, BigInteger::Index length, BigInteger::Sign sign);
23
24// Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
25std::ostream &operator <<(std::ostream &os, const BigUnsigned &x);
26
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).
29std::ostream &operator <<(std::ostream &os, const BigInteger &x);
30
31/*
32 * =================================
33 * BELOW THIS POINT are template definitions; above are declarations. See `NumberlikeArray.hh'.
34 */
35
36/*
37 * Converts binary data to a BigInteger.
38 * Pass an array `data', its length, and the desired sign.
39 *
40 * Elements of `data' may be of any type `T' that has the following
41 * two properties (this includes almost all integral types):
42 *
43 * (1) `sizeof(T)' correctly gives the amount of binary data in one
44 * value of `T' and is a factor of `sizeof(Blk)'.
45 *
46 * (2) When a value of `T' is casted to a `Blk', the low bytes of
47 * the result contain the desired binary data.
48 */
49template <class T>
50BigInteger 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;
55
56 // Allocate our block array
57 BigInteger::Blk *blocks = new BigInteger::Blk[numBlocks];
58
59 BigInteger::Index blockNum, pieceNum, pieceNumHere;
60
61 // Convert
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;
68 }
69
70 // Create the BigInteger.
71 BigInteger x(blocks, numBlocks, sign);
72
73 delete blocks;
74 return x;
75}
76
77#endif