Binary to Base Ten Converter

This is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//Binary to Base 10 converter
#include <iostream>
using namespace std;

int main ()
{
	unsigned long int num;
	int factor = 1;
	int remain;
	int val;


	cout << "Enter a binary number: ";
	cin >> num;	//binary number is entered

	while (num != 0) {
		remain = num % 10;
		val = remain * factor;
		num /= 10;
		factor *= 2;
		val += val;
	}

	cout << val;

	return 0;
}


I can't figure out what is wrong with it, but it isn't working. Any help would be appreciated!
Last edited on
Why are you adding val to itself? The calculation 3 lines previous wiped out the previous value of val.

Please use code tags (the <> formatting button) when posting code.

Sorry, I was new to the forum, I will from now on. So what would you recommend to fix it? I realized that the val +=val; line was adding val to itself, but how do i fix it so it just adds up each new val in each sequence through the loop?
@jonjanssen13

Try it this way. I changed num to a string, and then checked if the order was a 1, or 0. It works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Binary to Base 10 converter : main project file.

#include <iostream>
#include <string>

using namespace std;

int main ()
{
	string num;
	int factor = 1;
	int val=0,len;


	cout << "Enter a binary number: ";
	cin >> num;	//binary number is entered
	len = num.length();
	for (int x=len-1;x>=0;x--)
	{
		if (num[x] == '1')
			val+=factor;
		
		factor*=2;
	}

	cout << endl << val<< endl;;

	return 0;
}
This could work, but it doesn't check the validities.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
unsigned int bin2dec(unsigned long int n)
{
  unsigned int output = 0;
  while (n)
  {
    output *= 2;
    output += n%10;
    n /= 10;
  }
}

unsigned long int dec2bin(unsigned int n)
{
  unsigned long int output = 0;
  while (n)
  {
    output *= 10;
    output += n%2;
    n /= 2;
  }
}
Last edited on
@Stewbond

That's not quite right either. You must read the number from the right to the left, to get the correct result. Otherwise, an input of 1000, gives the answer of 1, and 1011 is 13, instead of 11.
Last edited on
@whitenite1 Thank you! That worked great!
Topic archived. No new replies allowed.