### binary to decimal conversion

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;
}
`binary[counter] = 1`
= is the assigment operator. == is the comparsion operator.
@romai
it doesn't work either way. i tried the comparison operator and it would show all kinds of errors. try it for yourself.
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
use itoa with base 2.
Last edited on
 ``12345678910111213141516171819`` ``````#include #include #include 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
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
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.
nickburress2k2 - My bad, forgot that :3
vasiqisbewildered - np :-)
Topic archived. No new replies allowed.