//Binary to Base 10 converter
#include <iostream>
usingnamespace std;
int main ()
{
unsignedlongint 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!
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?
//Binary to Base 10 converter : main project file.
#include <iostream>
#include <string>
usingnamespace 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;
}
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.