# C++ Converting BASE of a large number

Discussion in 'Software Development' started by kobel, Mar 2, 2005.

Not open for further replies.

Joined:
Apr 30, 2004
Messages:
13
I need some help in C++. Hope someone could give some help..

How could I change base of a very large number? For example I want to change the number 7146329081 into base 32768. I did this by hand and the answer is 6 21480 21497. I could do the last part (21497) but the rest I got stuck.

Here is the function that I have so far..

#include <vector>
#include <cmath>
#include <iostream>

const int BASE = 32768;
void normalization(const vector<int> &vec)
{
int carry = 0, digit = vec[0], x = 0, totalcarry = 0;
vector<int> temp;
while ( x < vec.size() )
{
digit *= 10; totalcarry *=10;
x++;
digit += vec[x];
if ( digit > BASE )
{
carry = floor ( (digit+0.0) / BASE );
digit = digit - carry * BASE;
totalcarry += carry;
if (totalcarry > base) // Stuck in here!
temp.push_back(digit);

}
}
cout << "Inside Carry : " << totalcarry << endl;
}

if u want to test it..put this in main :
vector <int> t;
t.push_back(7); t.push_back(1); t.push_back(4); t.push_back(6);
t.push_back(3); t.push_back(2); t.push_back(9); t.push_back(0);
t.push_back(8); t.push_back(1);

normalization(t);

Any help would greatly be appreciated...I spent alot of time already on this and getting frustrated...

Thanks

Joined:
Apr 30, 2004
Messages:
13
I formatted the code...but somehow it ended up all squezzed up to the left..

Joined:
Sep 1, 2004
Messages:
1,756
The modulo (%) operator would be useful here. Say you have an input number x in base 10, and you want to convert it to y in base 32768, the rightmost digit of y is x % 32768. Then you subtract the rightmost digit from x. To get the next digit of y (heading left) you would take x % 32768^2, then subtract that result from x, and so on.

Joined:
Apr 30, 2004
Messages:
13
The modulo works if you have a number that is less than 32 bits long...but for this problem I'm dealing with a very very large base 10 number that is 350-400 digits long. I simply want to add 2 very very large number together. The computer can't do this, unless I change the base to make it smaller for easier computation...

Joined:
Sep 1, 2004
Messages:
1,756
There are easier ways to do that! Do a search on Google for "c++ bignum", the bignum data type can be as large as you like.

As Seen On