Binary to Decimal Converter

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
int N=0, counter=0, counter1=0,counter2=0, temp=0, temp1=0,dec=0,result=0, moder=0;
cout<<"Please enter required binary number"<<endl;
cin>>N;
temp=N;
while(temp>=10)
{
temp=temp/10;
moder=moder*10;
counter++;
}
counter2=counter+1;
while(counter1<=counter)
{
dec=(N%moder)*pow(2,counter2);
N=N-moder;
moder=moder/10;
counter2--;
result=result+dec;
counter1++;
}
cout<<"Decimal number will be "<<result<<endl;
return 0;
}
........................................................................................................................
This is Binary to Decimal Converter. It's not working. Although Dry Run of this program works fine. I don't know what's problem.
Can any one find it's bug or bugs and fix it for me. Thanks!
Last edited on
Why are you re-inventing the wheel. Or is this a particular assignment you have been given?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <bitset>

using namespace std;

int main()
{
	string binary("01100100");
	unsigned long number = bitset<numeric_limits<unsigned long>::digits>(binary).to_ulong();

	return 0;
}
I have written a code recently that converts a Bin Num to Dec.
It looks like it works.
I put here the code for testing purposes.
Forum members, please, check it.

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
// bin to dec simple method

#include <iostream>
#include <cmath> //pow
#include <stdlib.h> //exit
using namespace std;

int main ()
{
    unsigned int num=0,bnum=0,rem=0,exp=0,sum=0;
    cout << "Type binary number: " << '\n';
    cin >> num; bnum=num; cout << '\n';

    do {
        rem = num % 10; if (!(rem==0||rem==1)) {exit (-1);}
        sum+= rem*pow(2,exp);
        num = (int) (num / 10);
        exp++;
    } while (num!=0);

    cout << "Binary number: " << bnum << '\n'
         << "Decimal number: " << sum << '\n';

    return 0;
}
thanks to all of you. . .But since I need to amend my code. I would like if any one correct mine and thanks for both of you. . .
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int N=1, counter=0, counter1=0, temp=1, result=0, moder=1;
cout<<"Please enter required binary number"<<endl;
cin>>N;
temp=N;
while(temp>=10)
{
temp=temp/10;
moder=moder*10;
counter++;
}
while(counter1<=counter)
{
temp= N/moder;
N=N-moder;
result +=(temp)*pow(2,counter);
moder=moder/10;
counter--;
counter1++;
}
cout<<"Decimal number will be "<<result<<endl;
return 0;
}
Thankyou all of you. I have found solution.
Topic archived. No new replies allowed.