All pastes #404650 Raw Edit

Binary - Decimal

public text v1 · immutable
·published 2007-03-21 04:09 UTC
rendered paste body
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace BinDec
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter Binary: ");
            string bin = Console.ReadLine();

            int dec = BinaryToDecimal(bin);

            if ( dec < 0 )
            {
                Console.WriteLine("You've supplied some invalid binary");
            }
            else
            {
                Console.WriteLine("Decimal: {0}", dec);
            }

            // Holding the console window open until enter is pressed
            Console.ReadLine();
        }

        static int BinaryToDecimal(string bin)
        {
            int a, b, c, d;
            int length, sum = 0;

            length = bin.Length - 1;

            for (a = 0; a <= length; a++)
            {
                c = Int32.Parse(bin[a].ToString());

                if ((c > 1) || (c < 0))
                {
                    return -1;
                }

                for (d = 1, b = length; b > a; b--)
                {
                    d *= 2;
                }

                sum += c * d;
            }

            return sum;
        }
    }
}