Using a stack to convert a number from binary to decimal

I have a program due for my Data Structures tomorrow and I need to figure out how to make it so it converts a number from binary to decimal with using a stack. I was able to figure it out without using a stack but stacks still really confuse me and part of the requirement is to use one. Any help would be awesome, thanks!
You can compare a stack to a pile of plates. You add a plate on the top(push) and normally you take one from the top(pop). Last in first out.
If you have a stack of chars and put 'a', 'b' and 'c' in it and remove them all you get first 'c', them 'b' and finally 'a' back - means in reversed order.

A little hint for your conversion.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int binary_do_decimal(const string& input)
{
  int output = 0, index = 0;
  stack<char> digits; // #include <stack>
  // add all digits to the stack
  for (char ch: input)
    digits.push(ch);

  while (!digits.empty())
  {
     char ch = digits.top();
     digits.pop();
     // TODO convert to ch to its numerical value and add to output.
     // remember that they are in reversed order so the first char is 2^index
  }
  return output.
}
Hope this makes sense
binary and hex are one to one. You can do it a nibble at a time if you convert it to hex first. You have to do it a bit at a time (4x more work) if you stick to decimal.

It's a little strange to use a stack for this.
1
2
3
4
5
    long n = 0;
    const char *s = "101100010101001";
    for ( ; *s; s++)
        n = 2 * n + (*s - '0');
    cout << n << '\n';

I would shift into N directly. I think its
N <<= (*s-'0'); //right?

after thinking about it, its efficient in reverse (integer to string binary) but not string to int to use the nibbles. The above shift is going to be faster than the string comparisons to do a lookup.

Its probably a 'do it this way' assignment. No one would really use a stack for this.
Last edited on
N <<= (*s-'0'); //right?

It would be nice if you could do it that way, but that actually says to shift N left by either 0 or 1 place; no actual 1's will be shifted in.

I wrote it in an arithmetical form, but it could be written in a bitwise form, too:
 
    n = (n << 1) |  (*s == '1');


It's analogous to accumulating the digits of a decimal number:
 
    n = n * 10 + (*s - '0');


Or indeed, any base:
 
    n = n * base + (isdigit(*s) ? *s - '0' : islower(d) ? *s - 'a' + 10 : *s - 'A' + 10);

Right.

n = (n << 1) | (*s == '1');

is what I meant, I just forgot how the shifter syntax works.
Topic archived. No new replies allowed.