I am building a class in C++ which can be used to store arbitrarily large integers. I am storing them as binary in a vector. I need to be able to print this vector in base 10 so it is easier for a human to understand. I know that I could convert it to an int and then output that int. However, my numbers will be much larger than any primitive types. How can I convert this directly to a string.
Here is my code so far. I am new to C++ so if you have any other suggestions that would be great too. I need help filling in the string toBaseTenString() function.
class BinaryInt { private: bool lastDataUser = true; vector<bool> * data; BinaryInt(vector<bool> * pointer) { data = pointer; } public: BinaryInt(int n) { data = new vector<bool>(); while(n > 0) { data->push_back(n % 2); n = n >> 1; } } BinaryInt(const BinaryInt & from) { from.lastDataUser = false; this->data = from.data; } ~BinaryInt() { if(lastDataUser) delete data; } string toBinaryString(); string toBaseTenString(); static BinaryInt add(BinaryInt a, BinaryInt b); static BinaryInt mult(BinaryInt a, BinaryInt b); }; BinaryInt BinaryInt::add(BinaryInt a, BinaryInt b) { int aSize = a.data->size(); int bSize = b.data->size(); int newDataSize = max(aSize, bSize); vector<bool> * newData = new vector<bool>(newDataSize); bool carry = 0; for(int i = 0; i < newDataSize; i++) { int sum = (i < aSize ? a.data->at(i) : 0) + (i < bSize ? b.data->at(i) : 0) + carry; (*newData)[i] = sum % 2; carry = sum >> 1; } if(carry) newData->push_back(carry); return BinaryInt(newData); } string BinaryInt::toBinaryString() { stringstream ss; for(int i = data->size() - 1; i >= 0; i--) { ss << (*data)[i]; } return ss.str(); } string BinaryInt::toBaseTenString() { //Not sure how to do this }
std::vector<bool>here, and you don't want a pointer to a vector. Something likestd::vector<unsigned> data;, plus an additional flag for the sign, would be the simplest./and%(preferably withintas well as withBinaryInt).vector<bool>isn't particularly large, regardless of how many elements it contains. And for something likeBinaryInt, you need value semantics.