Advertisement
Sekklow

Loops-BinaryToDecimal

Aug 16th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. using System;
  2.  
  3. /// <summary>
  4. /// Using loops write a program that converts a binary integer number
  5. /// to its decimal form. The input is entered as string. The output
  6. /// should be a variable of type long. Do not use the built-in .NET
  7. /// functionality.
  8. /// </summary>
  9. public class BinToDec
  10. {
  11.     public static void ConvertBinToDec(string input)
  12.     {
  13.         string[] inputArr = new string[input.Length];
  14.         double inputDecimal = 0;
  15.  
  16.         // Fill the inputArr array. Since string as like an array of chars it's rather easy
  17.         for (int i = 0; i < input.Length; i++)
  18.         {
  19.             inputArr[i] = char.ToString(input[i]);
  20.             if (int.Parse(inputArr[i]) != 0 && int.Parse(inputArr[i]) != 1)
  21.             {
  22.                 // If the input is invalid (e.g. 5) you will be prompted to re-enter valid input.
  23.                 Console.WriteLine("Invalid Input! Try again: ");
  24.                 Main();
  25.             }
  26.         }
  27.  
  28.         // Array is reversed to prevent trailing zeroes at the beginning to increment the
  29.         // power we use in the calculation.
  30.         Array.Reverse(inputArr);
  31.  
  32.         for (int i = 0; i < inputArr.Length; i++)
  33.         {
  34.             inputDecimal += double.Parse(inputArr[i]) * Math.Pow(2, i);
  35.         }
  36.  
  37.         Console.WriteLine(inputDecimal);
  38.     }
  39.  
  40.     static void Main()
  41.     {
  42.         string input = Console.ReadLine();
  43.  
  44.         ConvertBinToDec(input);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement