Advertisement
Guest User

Binary to Decimal

a guest
Apr 11th, 2015
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.86 KB | None | 0 0
  1. // Problem 2. Binary to decimal
  2.  
  3. // Write a program to convert binary numbers to their decimal representation.
  4.  
  5. using System;
  6.  
  7. class BinaryToDecimal
  8. {
  9.     static void Main()
  10.     {
  11.         // input
  12.         Console.WriteLine("Please, enter a binary number:");
  13.         string number = Console.ReadLine();
  14.  
  15.         // custom conversion method
  16.         int decNumber = 0;
  17.         int index = 0;
  18.         for (int i = number.Length - 1; i >= 0; i--)
  19.         {
  20.             decNumber += (int)(int.Parse(number[i].ToString()) * Math.Pow(2, index));
  21.             index++;
  22.         }
  23.         Console.WriteLine("\nConverted using the custom method: {0}", decNumber);
  24.  
  25.         // conversion using embedded functionality
  26.         decNumber = Convert.ToInt32(number, 2);
  27.         Console.WriteLine("\nConverted using the embedded functionality: {0}\n", decNumber);
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement