开发者

Converting Binary to Decimal using while loop in C++

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;

}


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


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;
}


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜