lmarkov

Decimal To Binary

Jan 29th, 2013
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. using System;
  2.  
  3. class DecimalToBinary
  4. {
  5.     static void Main()
  6.     {
  7.         int decimalNumber = Input();
  8.  
  9.         BinaryRepresentation(decimalNumber);
  10.  
  11.         Main();
  12.     }
  13.  
  14.     private static void BinaryRepresentation(int decimalNumber)
  15.     {
  16.         int remainder;
  17.         string result = string.Empty;
  18.  
  19.         if (decimalNumber == 0)
  20.         {
  21.             result = "0000";
  22.         }
  23.         else
  24.         {
  25.             while (decimalNumber > 0)
  26.             {
  27.                 remainder = decimalNumber % 2;
  28.                 decimalNumber /= 2;
  29.                 result = remainder.ToString() + result;
  30.             }
  31.         }
  32.         Console.WriteLine("Binary representation: {0}" + Environment.NewLine, result);
  33.     }
  34.  
  35.     private static int Input()
  36.     {
  37.         int decimalNumber;
  38.         do
  39.         {
  40.             string message = "Please enter value between 0 and " + int.MaxValue + " !";
  41.             Console.WriteLine(message);
  42.             Console.Write("Enter decimal number: ");
  43.         } while (!(int.TryParse(Console.ReadLine(), out decimalNumber) && decimalNumber >= 0 && decimalNumber <= int.MaxValue));
  44.         return decimalNumber;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment