DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   binary to decimal (http://www.daniweb.com/forums/thread150474.html)

egolovin Oct 10th, 2008 8:55 pm
binary to decimal
 
can someone look at this? in theory it should work but i cant figure it out
thanks in advance
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
void binToDec(string getBinary);
int main()
{
        string getBinary;
        cout<<"Enter a Binary Number:"<<endl;
        cin>>getBinary;
        binToDec(getBinary);
       
return 0;
}
void binToDec(string getBinary)
{
        int setLength,total=0;
        double placeholder=0;
        setLength=getBinary.size();
       
        for(int i=setLength;i>0;i--)
        {
                int num=pow(2.0,placeholder);
                int test=getBinary[i];
                if (test==1)
                {
                        total=total+num;
                }

                placeholder=placeholder +1;
       
        }
        cout<<total<<endl;


}

Rhohitman Oct 10th, 2008 9:06 pm
Re: binary to decimal
 
I guess using string is not the good idea.
What we use to do was.... some how take the binary in the int or long.

then take a loop and extract the element one by one form the last...

I guess this is the efficient method.. some how you are wasting too much memory space using string.

int dec;
int bin;
cin>>bin;

for(int i=0; bin!=0; bin/=10)
  dec+=bin%10*pow(2, i++);

egolovin Oct 10th, 2008 9:12 pm
Re: binary to decimal
 
oh sorry i forgot to add i have to use string as binary this is hw for school. pow only works with double. :(

Rhohitman Oct 10th, 2008 9:20 pm
Re: binary to decimal
 
Quote:

Originally Posted by egolovin (Post 709904)
oh sorry i forgot to add i have to use string as binary this is hw for school. pow only works with double. :(


if you are such crazy about the string.
then you must subtract 48 from the each character of the string

as ASCII value of 1 is 49
when you subtract 49-48 = 1
then you can use it as normally

dougy83 Oct 10th, 2008 10:52 pm
Re: binary to decimal
 
What
Quote:

Originally Posted by egolovin (Post 709894)
can someone look at this? in theory it should work but i cant figure it out
thanks in advance
        if (test==1)

That line should be
           if (test == '1')

1 is different to '1' (character code 49, as Rhohitman said). Also, for powers of 2 you don't have to use pow(). Using the shift operator<< works fine for integers. So
pow(2., x)
can be replaced with
1<<x

egolovin Oct 11th, 2008 8:53 am
Re: binary to decimal
 
Thanks alot :d


All times are GMT -4. The time now is 6:55 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC