-5

I would like to change a Binary Number to a Decimal Number.

My problem is that my programme would not enter even the for loop, hence my sum is always 0. I don't know where is the error of my for loop.

My idea is that for a number like 1010, I will divide it by 10 and get the last digit which is 0, and then multiply it with 2^0, and then 1010 will be divide by 10 to be 101 and the loop continues.

Here is what i have tried so far:

cout<<"Please Enter a Binary Digit Number"<<endl;
cin>>num;
sum=0;
x=0;

for (int i=num; i/10 == 0; i/10) {
    sum+=num%10*2^x;
    num/=10;
    x++;
}

cout<<sum;
dirtydanee
  • 6,081
  • 2
  • 27
  • 43
  • 2
    [do you know what the `^` operator means in C++?](http://stackoverflow.com/q/4843304/995714) – phuclv Dec 24 '16 at 14:52

2 Answers2

1

Presumably you're inviting the user to enter a binary string at the console. In this case you have to collect the digits as a string of characters.

something more like this?

using namespace std;
std::string bin;
cout<<"Please Enter a Binary Digit Number"<<endl;
cin>>bin;

int sum=0;
int bit=1;
for (auto current = std::rbegin(bin) ; current != std::rend(bin) ; ++current, bit <<= 1)
{
    if (*current != '0')
        sum |= bit;
}

cout<<sum << std::endl;

or prior to c++11 (I assume that this is a school project - they are likely to have out of date kit):

for (auto current = bin.rbegin() ; current != bin.rend() ; ++current, bit <<= 1)
{
    if (*current != '0')
        sum |= bit;
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
0
working:-

    #include<iostream>
    using namespace std;
    int num,sum,x;
    int main()
    {
    cout<<"Please Enter a Binary Digit Number"<<endl;
    cin>>num;
    sum=0;
    x=0;

    long base=1,dec=0;
//Binary number stored in num variable will be in loop until its value reduces to 0
    while(num>0)
    {

        sum=num%10;
//decimal value summed ip on every iteration
        dec = dec + sum * base;
//in every iteration power of 2 increases
        base = base * 2;
//remaining binary number to be converted to decimal
        num = num / 10;
        x++;
    }

    cout<<dec;
    return 0;
    }
Codesingh
  • 3,316
  • 1
  • 11
  • 18