Advertisement
stefanpu

Convert decimal to binary refactoring

Feb 14th, 2013
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. /*
  5.  * Write a program to convert decimal numbers to their binary representation.
  6.  */
  7.  
  8. namespace ConvertDecimalToBinary
  9. {
  10.     class ConvertDecimalToBinary
  11.     {
  12.         static void Main()
  13.         {
  14.             int decNumber = InputDecimalNumber();
  15.  
  16.             //Заб: Името е малко по-дълго за да не именувам метода като класа:
  17.             //ако беше ConvertDecimalToBinary това щеше да е лошо именуваме защото
  18.             // съвпада с името на конструктора на класа.
  19.            
  20.             List<int> bits = ConvertDecimalNumberToBinary(ref decNumber);
  21.  
  22.             //празен ред за да знаем, че двата реда са различни части от програмата.
  23.  
  24.             PrintBinaryNumber(bits);
  25.         }
  26.  
  27.         private static void PrintBinaryNumber(List<int> bits)
  28.         {
  29.             Console.Write("The binary representation of the number is: ");
  30.             for (int i = bits.Count - 1; i >= 0; i--)
  31.             {
  32.                 Console.Write(bits[i]);
  33.             }
  34.             Console.WriteLine();
  35.         }
  36.  
  37.         private static List<int> ConvertDecimalNumberToBinary(ref int decNumber)
  38.         {
  39.             List<int> bits = new List<int>();
  40.             while (decNumber > 0)
  41.             {
  42.                 bits.Add(decNumber % 2);
  43.                 decNumber /= 2;
  44.             }
  45.             return bits;
  46.         }
  47.  
  48.         private static int InputDecimalNumber()
  49.         {
  50.             Console.Write("Please enter a number between 1 and {0}: ", int.MaxValue);
  51.             int decNumber = int.Parse(Console.ReadLine());
  52.             return decNumber;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement