Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class BinaryToDecimalNum
- {
- static void Main()
- {
- //Write a program to convert binary numbers to their decimal representation.
- string numberToConvert = Console.ReadLine();//Read the input from the console
- Console.WriteLine(ConvertBinaryToDecimal(numberToConvert));
- }
- static int ConvertBinaryToDecimal(string number) //Converts the number from binary to decimal numeral system
- {
- List<int> numberAsDigits = new List<int>(); //List to store the digits of our number
- int decimalNumber = 0; //The result number
- bool isNegativeNum = false;
- foreach (char digit in number)//Output the digits from the string into the list
- {
- numberAsDigits.Add((digit - '0'));
- }
- 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)
- {
- isNegativeNum = true; //Indicate that it is negative
- numberAsDigits.RemoveAt(0); //Remove from the list the 32nd position (0 in the list index)
- }
- for (int i = numberAsDigits.Count - 1, power=0 ; i >= 0; i--, power++) //Do the maths by the formula
- {
- decimalNumber += numberAsDigits[i]*(int)(Math.Pow(2,power));
- }
- if (isNegativeNum== true)//Go back to see if we need a minus sign
- {
- decimalNumber *= -1;//Add the minus sign
- }
- return decimalNumber;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement