Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting many bits to Base 10
    text
    copied!<p>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.</p> <p>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 <code>string toBaseTenString()</code> function. </p> <pre><code>class BinaryInt { private: bool lastDataUser = true; vector&lt;bool&gt; * data; BinaryInt(vector&lt;bool&gt; * pointer) { data = pointer; } public: BinaryInt(int n) { data = new vector&lt;bool&gt;(); while(n &gt; 0) { data-&gt;push_back(n % 2); n = n &gt;&gt; 1; } } BinaryInt(const BinaryInt &amp; from) { from.lastDataUser = false; this-&gt;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-&gt;size(); int bSize = b.data-&gt;size(); int newDataSize = max(aSize, bSize); vector&lt;bool&gt; * newData = new vector&lt;bool&gt;(newDataSize); bool carry = 0; for(int i = 0; i &lt; newDataSize; i++) { int sum = (i &lt; aSize ? a.data-&gt;at(i) : 0) + (i &lt; bSize ? b.data-&gt;at(i) : 0) + carry; (*newData)[i] = sum % 2; carry = sum &gt;&gt; 1; } if(carry) newData-&gt;push_back(carry); return BinaryInt(newData); } string BinaryInt::toBinaryString() { stringstream ss; for(int i = data-&gt;size() - 1; i &gt;= 0; i--) { ss &lt;&lt; (*data)[i]; } return ss.str(); } string BinaryInt::toBaseTenString() { //Not sure how to do this } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload