binary to decimal conversion

Oct 18, 2010 at 4:42am
This is the program I have for the conversion of binary numbers to decimal. The program runs pretty well but miscalculates the decimal value. It basically treats every number as 1 in the binary string. So if you were to input binary numbers 0000 or 1111, it would give the decimal as 15. Any help would be appreciated.

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
string binary;
cout << "Enter the binary value you wish to convert into decimal: " << endl;
cin >> binary;

int counter = 0;
double decimal = 0;

while (counter < binary.size())
{
if(binary[counter] = 1)
{
decimal = (decimal + pow(2.0,counter));
}
else
decimal = (decimal +pow(0.0, counter));

counter++;
}
cout << "The decimal representation of the given binary is: " << decimal << endl;

return 0;
}
Oct 18, 2010 at 10:59am
binary[counter] = 1
= is the assigment operator. == is the comparsion operator.
Oct 18, 2010 at 11:15pm
@romai
it doesn't work either way. i tried the comparison operator and it would show all kinds of errors. try it for yourself.
Oct 19, 2010 at 5:19am
It is the operator plus you are indexing the array from left to right instead of from right to left.And the constant 1 is not a character.'1' is.Cheers.
Last edited on Oct 19, 2010 at 5:21am
Oct 19, 2010 at 10:00am
use itoa with base 2.
Last edited on Oct 19, 2010 at 10:00am
Oct 20, 2010 at 4:21pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <cmath>

int main()
{
  std::string binary;
  double decimal = 0;

  std::cout << "Enter the binary value you wish to convert into decimal: " << endl;
  std::cin >> binary;

  for(int counter = 0; counter < binary.size(); counter++)
    if(binary.c_str()[counter] == '1')
      decimal += pow(2, counter);

  cout << "The decimal representation of the given binary is: " << decimal << endl;
  return 0;
}


As for itoa, according to http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/ - "This function is not defined in ANSI-C and is not part of C++."
Last edited on Oct 20, 2010 at 4:22pm
Oct 20, 2010 at 8:53pm
Kiana,

You are missing STD to endl and cout, since you don't have the using directive at the top anymore.

std::endl
std::cout
Oct 20, 2010 at 9:26pm
Kiana, thank you so much. I just changed the 1 to '1' and that made all the difference, else i used my own code. anyway, thank you for your time.
Oct 25, 2010 at 10:08pm
nickburress2k2 - My bad, forgot that :3
vasiqisbewildered - np :-)
Topic archived. No new replies allowed.