Advertisement
sylviapsh

Binary To Decimal Number Converter

Jan 18th, 2013
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class BinaryToDecimalNum
  6. {
  7.   static void Main()
  8.   {
  9.     //Write a program to convert binary numbers to their decimal representation.
  10.  
  11.     string numberToConvert = Console.ReadLine();//Read the input from the console
  12.     Console.WriteLine(ConvertBinaryToDecimal(numberToConvert));
  13.   }
  14.  
  15.   static int ConvertBinaryToDecimal(string number) //Converts the number from binary to decimal numeral system
  16.   {
  17.     List<int> numberAsDigits = new List<int>(); //List to store the digits of our number
  18.     int decimalNumber = 0; //The result number
  19.     bool isNegativeNum = false;
  20.  
  21.     foreach (char digit in number)//Output the digits from the string into the list
  22.     {
  23.       numberAsDigits.Add((digit - '0'));
  24.     }
  25.  
  26.     if (numberAsDigits.Count == 32 && numberAsDigits[0] == 1) //Check if the binary number is negative(i.e. the 32nd position is 1 from signed magnitude theory)
  27.     {
  28.       isNegativeNum = true; //Indicate that it is negative
  29.       numberAsDigits.RemoveAt(0); //Remove from the list the 32nd position (0 in the list index)
  30.     }
  31.     for (int i = numberAsDigits.Count - 1, power=0 ; i >= 0; i--, power++) //Do the maths by the formula
  32.     {
  33.       decimalNumber += numberAsDigits[i]*(int)(Math.Pow(2,power));
  34.     }
  35.     if (isNegativeNum== true)//Go back to see if we need a minus sign
  36.     {
  37.       decimalNumber *= -1;//Add the minus sign
  38.     }
  39.     return decimalNumber;
  40.   }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement