int ten digit limit?

A problem from a beginner's howto on C++. Using g++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int num;
int factor;
int conv;
int remainder;
int dec;
int figure;

int main()
{
  factor = 1;
  conv = 0;

  cout << "Enter binary number: ";
  cin >> num;
  figure = num;

  while ( num > 0)
    {
      remainder = num % 10;
      conv = ( factor * remainder) + conv;
      factor = factor * 2;
      dec = conv;
      num = num / 10;
    }

  cout << endl << figure << " to decimal is " << dec << endl;
  return 0;
 }


The program converts a binary to decimal. I encounter a problem, however when I try to enter 11 digit numbers and beyond. The program displays the digit as 0 and the subsequent decimal solution as 0. I suspect this might have something to do with my 32bit processor? If not, then what is the limit about? Links and suggestions appreciated, thank you.
That's it exactly. The largest value an int can hold is 4294967295, which is ten digits. Even though the user is entering a number like 100101, it is still read as a decimal number, hence the limit in digits.

I would suggest getting a string from the user, verify that it is composed of nothing but '0's and '1's, and then convert the string, character by character, to a decimal number. Then your limit will be 32 digits/bits. Well, 31 if you continue to use a signed int.

Have fun!
Topic archived. No new replies allowed.