0

I am currently reading a book on C++ and there is a task which asks the reader to convert a binary number (inputted by the user) to a decimal equivalent. So far I have the following code, but all it does is output 0. Any idea what has gone wrong?

#include <iostream>
using namespace std;

int main()
{
int x, b = 10, decimalValue = 0, d, e, f, count = 1, counter = 0;
cout << "Enter a binary number: ";
cin >> x;
x /= 10;
while( x > 0)
{
count++;
x = x/10;
}
while (counter < count)
{
      if (x == 1)
      {
            f = 1;
      }
      else{
           f = x % b;
      }
      if (f != 0)
      {
            if (counter == 0)
            {
               decimalValue = 1;
            }
            else
            {
               e = 1;
               d = 1;
               while (d <= counter)
               {
                  e *= 2;
                  d++;
               }
               decimalValue += e;
            }
      }
      x /= b;
      counter++;
}
cout << decimalValue << endl;
system("pause");
return 0;

}

4 Answers 4

2

Because the while( x > 0) loop only stops when x <= 0. Besides, cin >> x lets the user input a decimal number.

Sign up to request clarification or add additional context in comments.

3 Comments

I have checked that part of the code. All it does is find out how many digits there are in the number inputted.
@Emile: no it doesn't. The x = x/10; statement resets x in every iteration until it's zero, and then you've lost its value.
oh.. Thanks :). Fixed it now. I guess I missed that part
2

After that bit of code:

while( x > 0)
{
count++;
x = x/10;
}

x is always 0, so put x into a temporary variable that you use to compute count:

int tmp = x;

while(tmp  > 0)
{
   count++;
   tmp  = tmp /10;
}

1 Comment

It's more elegant to compute with tmp in the loop, that saves you the assignment afterwards.
2

I've written some sample code. Have a read and see if you can understand what I've done. Ask questions about any bits that are confusing.

#include <iostream>
#include <string>
#include <cassert>
#include <stdexcept>
#include <limits>

unsigned DecodeBinary(const std::string &sBin)
{
    // check for a bad string
    if (sBin.npos != sBin.find_first_not_of("01"))
        throw std::invalid_argument("Badly formed input string");

    // check for overflow
    if (sBin.length() > std::numeric_limits<unsigned>::digits)
    {
        throw std::out_of_range("The binary number is too big to "
                                "convert to an unsigned int");
    }

    // For each binary digit, starting from the least significant digit, 
    // set the appropriate bit if the digit is not '0'
    unsigned nVal = 0;
    unsigned nBit = 0;
    std::string::const_reverse_iterator itr;
    for (itr=sBin.rbegin(); itr!=sBin.rend(); ++itr)
    {
        if (*itr == '1')
            nVal |= (1<<nBit);
        ++nBit;
    }
    return nVal;
}

int main()
{
    try
    {
        std::cout << "Enter a binary number: ";
        std::string sBin;
        std::cin >> sBin;

        unsigned nVal = DecodeBinary(sBin);

        std::cout << "\n" << sBin << " converts to " << nVal << "\n";
        return 0;
    }
    catch (std::exception &e)
    {
        std::cerr << "\n\nException: " << e.what() << "\n";
        return 1;
    }
}

Consider an input of "1101"

Start with least significant digit, index 0
Index 3 2 1 0
Value 1 1 0 1

It is a "1" so set bit 0 of the output to be 1 (00000001 = 1).

Next digit is a zero so do nothing.
Next digit is a '1', so set bit 2 to be 1 (00000101 = 5)
Next digit is a '1', so set bit 3 to be 1 (00001101 = 13)

2 Comments

Thanks. I am still learning C++, so there are some aspects of the code I do not understand. However I did try it out and it worked much better than mine (my code could only accept max 10 digit binary numbers). I'll have a deeper look at it soon and hopefully I will learn something new!
OK. If you have specific questions, then just ask them.
0

Simplest way I know of to accomplish this would be the following:

int binaryToInteger(string binary) {
  int decimal = 0;
  for (char x : binary)  {
      decimal = (decimal << 1) + x - '0';
  }
  return decimal;
}

For instance, "101" would be converted as follows:
1) decimal = (0 << 1) + 1 = 1
2) decimal = (1 << 1) + 0 = 2
3) decimal = (2 << 1) + 1 = 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.