views:

454

answers:

3

How can I create a program to convert binary to decimal using a stack in C#?

A: 

CConvert any number in binary to decimal in C# console application.

using System;

class Program{

static void Main(string[] args){
 try{
   int i = ToDecimal(args[0]);
   Console.WriteLine("\n{0} converted to Decimal is {1}",args[0],i);
   }catch(Exception e){
   Console.WriteLine("\n{0}\n",e.Message);
   }
}

public static int ToDecimal(string bin)
{
    long l = Convert.ToInt64(bin,2);
    int i = (int)l;
    return i;
}
}
balaweblog
Wow, where to start....
FlySwat
A: 
  1. Implement a stack
  2. Convert binary to decimal
  3. ????
  4. Profit!
Joel Coehoorn
This is what happens when I answer questions after midnight ;)
Joel Coehoorn
Let me guess, that was the South Park episode that played tonight? lol
Matt R
1. Pile stuff up
George Jempty
+4  A: 

Here is a hint, this snippet converts a decimal integer to binary using a Stack, you just have to invert the process :-P

        int num = 50;
        Stack<int> stack = new Stack<int>();
        while (num != 0)
        {
            stack.Push(num % 2);
            num /= 2;
        }

        while (stack.Count > 0)
        {
            Console.Write(stack.Pop());
        }
CMS