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
2008-11-15 06:00:24
Wow, where to start....
FlySwat
2008-11-15 13:30:49
+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
2008-11-15 06:23:40