Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

C++ base conversion problem


ghost's Avatar
0 0

I'm trying to write a program to convert from decimal to some base, n, where 1<n<=10 (for now). from decimal works (at least to binary), but my conversion back is saying 11011 in decimal is 8021. my code (x is the number to convert, n is the base to convert from:

//n^i*((x%10^(i+1))-(x%10^i))
unsigned int toDecimal(int x, int n){

	unsigned int sum=0;
	for(int i=0;i&lt;=(int)(1+log10((double)x));i++){

		sum+=(int)pow((double)n, i)*((x%(int)pow(10.0, (i+1)))-(x%(int)pow(10.0, i)));

	}

	return sum;

}

JDavidC's Avatar
Member
0 0

The code you have is very hard to read, I'd suggest a total rewrite.

I had to look some stuff up on Google, you may need to as well.

If you want to convert from decimal to another base, the itoa function can do this for you, although you will get a string. The itoa function is not part of ANSI-C or C++, but some compilers support it. atoi may be a good way of converting the string you get back to an integer if you need it in that format.

For the reversed conversion though, this gets more difficult. You may still want to use itoa or something like sprintf to get n as a string. Then you simply reverse the order of the string. Once that's done, do something like

// to raise the digit in the reversed string by when adding to sum.
// Subtract the ASCII value of 0 from the ASCII value of
// the character at the index to convert it to the corresponding number.
sum += (int)pow(b, i) * ((int)reversedString[i] - (int)&#39;0&#39;); 

in a loop over each character in your reversed string.


ghost's Avatar
0 0

So in trying to explain my code, I came to the realization that the output 8021 to the binary number 1011 makes perfect sense based on that code. I forgot the division by 10^i. added that and it works perfectly. it still looks much better written in mathematical notation, though. also, I've already done this with a string. I wanted to do it entirely with math.


JDavidC's Avatar
Member
0 0

Basically, your code should divide the extracted number by 10^i to convert it to a digit, like this? I looked at the code again and figured out how you were trying to extract a digit.

//n^i*(((x%10^(i+1))-(x%10^i))/10^i) unsigned int toDecimal(int x, int n){

unsigned int sum=0;
for(int i=0;i&lt;=(int)(1+log10((double)x));i++){

	sum+=(int)pow((double)n, i)*(((x%(int)pow(10.0, (i+1)))-(x%(int)pow(10.0, i)))/(int)pow(10, i));

}

return sum;

}


ghost's Avatar
0 0

exactly, but looking at it again, I realized I didn't even need to separate the digits like that, as dividing the by the power of 10 will truncate any rational part, anyway, so that line works just like this

sum+=(int)pow((double)n, i)*((x%(int)pow(10.0, (i+1)))/(int)pow(10.0, i));