binary to decimal convertor

tux4life 0 Tallied Votes 220 Views Share

This snippet allows you to convert a text representation(*) of a binary number to a decimal number :)

(*): With 'text representation' I mean for example a string containing "1001" or "10001110011", etc. ...

#include <iostream>
#include <string>

using namespace std;

unsigned int pow(unsigned int a, unsigned int n);

int main()
{
    string binary;
    unsigned int decimal = 0;
	
    cout << "Enter a binary number: ";
    cin >> binary;

    for(int i = binary.length()-1; i >= 0; i--) {
        if(binary[i] > '1' || binary[i] < '0') {
            cout << "Invalid binary number!" << endl;
            return 1;
        } else {
            decimal += (binary[i] - '0') * pow(2, (binary.length()-i-1));
        }
    }
	
    cout << "Decimal: " << decimal << endl;	
    return 0;
}

unsigned int pow(unsigned int a, unsigned int n)
{
    unsigned int r = 1;
    while( n-- > 0 ) r *= a;
    return r;
}

Dani AI

Generated

Good starting point, — and useful commentary from and . For clarity and safety when you just need an unsigned decimal value, prefer a library conversion that handles parsing and overflow for you. The snippet below keeps input validation, accepts an optional 0b/0B prefix, and reports overflow instead of silently wrapping.

#include <iostream>
#include <string>
#include <stdexcept>

int main() {
  std::string s;
  if (!(std::cin >> s)) return 0;

  if (s.size() >= 2 && s[0] == '0' && (s[1] == 'b' || s[1] == 'B'))
    s.erase(0,2);

  if (s.empty()) { std::cerr << "Empty input\n"; return 1; }

  for (char c : s)
    if (c != '0' && c != '1') { std::cerr << "Invalid binary digit\n"; return 1; }

  try {
    unsigned long long value = std::stoull(s, nullptr, 2);
    std::cout << value << '\n';
  } catch (const std::out_of_range&) {
    std::cerr << "Value too large for unsigned long long\n"; return 2;
  } catch (const std::invalid_argument&) {
    std::cerr << "Invalid argument\n"; return 3;
  }
}

Notes and practical tips:

  • std::stoull(..., 2) gives concise parsing and throws on overflow; handle out_of_range if input may exceed 64 bits. This avoids manual power loops or repeated multiplications.
  • If you need fixed-width interpretation (32/64 bits) or two's-complement semantics, use std::bitset<N> or implement explicit signed conversion. As pointed out, shifting is fast — but always check for overflow.
  • For arbitrarily large binaries, use a big-integer library (for example Boost.Multiprecision) and parse left-to-right multiplying by 2 and adding the digit.
  • Avoid signed/unsigned index bugs (the classic for (int i = s.length()-1; i >= 0; --i) pitfall). Prefer reverse iterators or std::string::size_type for robust indexing.
  • Small style: avoid using namespace std; in real projects and prefer explicit types like std::uint64_t when size matters.

These suggestions preserve the simple intent in the thread while improving robustness, overflow handling, and maintainability.

amrith92 119 Junior Poster

Nice code! But maybe the function name pow should be changed, to avoid any ambiguity caused if anybody chooses to include <cmath> with that :) ...

tux4life 2,072 Postaholic

Yep, there you've got a point!
For those who are using the cmath library:
Change the name of the pow function to apow/mypow/pow2 or whatever you like :P

William Hemsworth 1,339 Posting Virtuoso

Here's how I would have done it:

#include <iostream>
using namespace std;

int main() {
  char binary[33]; // 32bit + '\0'
  unsigned int decimal = 0;

  cout << "Enter binary:\n> ";

  cin.getline( binary, 32 );
  unsigned int exp = 1;

  for (int i = (int)strlen( binary ) - 1; i >= 0; --i) {
    if ( binary[i] == '1' )
      decimal += exp;

    exp <<= 1;
  }

  cout << "\nDecimal:\n> " << decimal;

  cin.ignore();
}
tux4life 2,072 Postaholic

I'm glad to know that there was actually no need for a separate function like pow, the bit shifting is a superior method to multiplicate it every time by two!
And William, your program will threat any other value than '1' as a '0', this isn't wrong IMO, but I only wanted to let you know in case you didn't (but probably you did know this already, because you're always one step ahead :))
I learned again from your code, you're superior in writing efficient and very easy to understand code :) !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.