Converting binary to decimal loop problem

Hello everyone, I've been trying to debug this problem for a while but the results make no sense to me.

cin >> binary;
decimal = converter(binary);

int converter(int binary)
{
int holder, number, digits;
digits = (int)log10(binary) + 1;


number = 0;
for (int i = 1; i <= digits; i++)
{
holder = binary - ((binary/((int)(pow(10.,i))))*(pow(10.,i)));
cout << holder << endl;
holder /= ((int)(pow(10.,(i-1))));
cout << holder << endl << endl;
number += pow(2., (i-1))*holder;
}
return number;
}

Here's the code, what's really strange is that this works for numbers that are less than 4 digits long. For example, 1111 will come out to be 15 like it should. However, anything longer such as 10101 will just be wrong.

From the cout's of the holder, the second iteration of the loop seems to have an error. The real mind boggler is that the rest of the loop works just fine, it's just the second iteration that comes out to be a giant negative number.
Perhaps you are crossing a maximum? Check the maximum value an int can hold.

1
2
3
4
5
6
7
8
#include <iostream>
#include <limits>
 
int main(void)
{
std::cout << std::numeric_limits<int>::max() << std::endl;
return 0 ;
}
Last edited on
Topic archived. No new replies allowed.