Advertisement
vlad0

Numeral 1

Jan 15th, 2013
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace _01.DecimalToBinary
  7. {
  8.     class DecimalToBinary
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             //Console.WriteLine("Enter decimal number: ");
  13.             //int enteredNumber = int.Parse(Console.ReadLine());
  14.  
  15.             int enteredNumber = 2-53;
  16.  
  17.             string binaryNumber = ConvertToBinary(enteredNumber);
  18.             Console.WriteLine(binaryNumber);
  19.             Console.WriteLine(Convert.ToString(enteredNumber,2));
  20.         }
  21.  
  22.         private static string ConvertToBinary(int enteredNumber)
  23.         {
  24.             StringBuilder calculations = new StringBuilder();
  25.             StringBuilder binary = new StringBuilder();
  26.             int negative = 0; //var for negative numbers
  27.  
  28.             if (enteredNumber<0)
  29.             {
  30.                 binary.Append(1);
  31.                 enteredNumber = enteredNumber * (-1); //make the value positive
  32.                 negative = 1; //remeber it is negative
  33.             }
  34.             //find the binary members
  35.             while (enteredNumber!=0)
  36.             {
  37.                 calculations.Append(enteredNumber % 2);
  38.                 enteredNumber /= 2;
  39.             }
  40.             //we got the binary memberse reversed so we have to reverse them
  41.             //and get them in the right way
  42.             char[] reverse = calculations.ToString().ToCharArray();
  43.             calculations.Clear();//we will use this second time so we have to clear it
  44.             int length = reverse.Length;
  45.            
  46.             for (int i = length-1; i >=0; i--) //starting from length-1 bevause it is reversed
  47.             {
  48.                 calculations.Append(reverse[i]);
  49.             }
  50.             if (negative == 1)// if it is negative we should make the 32nd bit to 1
  51.             {
  52.                 binary.Append(calculations.ToString().PadLeft(32 - negative, '0'));
  53.             }
  54.             else //if it isnot negative we just print it
  55.             {
  56.                 binary.Append(calculations.ToString());
  57.             }
  58.  
  59.             return binary.ToString();
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement