Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /// <summary>
- /// Using loops write a program that converts a binary integer number
- /// to its decimal form. The input is entered as string. The output
- /// should be a variable of type long. Do not use the built-in .NET
- /// functionality.
- /// </summary>
- public class BinToDec
- {
- public static void ConvertBinToDec(string input)
- {
- string[] inputArr = new string[input.Length];
- double inputDecimal = 0;
- // Fill the inputArr array. Since string as like an array of chars it's rather easy
- for (int i = 0; i < input.Length; i++)
- {
- inputArr[i] = char.ToString(input[i]);
- if (int.Parse(inputArr[i]) != 0 && int.Parse(inputArr[i]) != 1)
- {
- // If the input is invalid (e.g. 5) you will be prompted to re-enter valid input.
- Console.WriteLine("Invalid Input! Try again: ");
- Main();
- }
- }
- // Array is reversed to prevent trailing zeroes at the beginning to increment the
- // power we use in the calculation.
- Array.Reverse(inputArr);
- for (int i = 0; i < inputArr.Length; i++)
- {
- inputDecimal += double.Parse(inputArr[i]) * Math.Pow(2, i);
- }
- Console.WriteLine(inputDecimal);
- }
- static void Main()
- {
- string input = Console.ReadLine();
- ConvertBinToDec(input);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement