Advertisement
Teodor92

SignedShort

Jan 15th, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. class SignedShort
  6. {
  7.     static List<short> DecToBin(short num)
  8.     {
  9.         List<short> bin = new List<short>();
  10.         while (num != 0)
  11.         {
  12.             bin.Add((short)(num % 2));
  13.             num = (short)(num / 2);
  14.         }
  15.         bin.Reverse();
  16.         return bin;
  17.     }
  18.     static string endingNums(string strNum, int endingNum)
  19.     {
  20.         StringBuilder newNum = new StringBuilder();
  21.         while (newNum.Length != 16 - strNum.Length)
  22.         {
  23.             newNum.Append(endingNum);
  24.         }
  25.         newNum.Append(strNum);
  26.         return newNum.ToString();
  27.     }
  28.     static void Main()
  29.     {
  30.         short number = short.Parse(Console.ReadLine());
  31.         StringBuilder endNum = new StringBuilder();
  32.         if (number >= 0)
  33.         {
  34.             List<short> NumInBin = DecToBin(number);
  35.             foreach (var item in NumInBin)
  36.             {
  37.                 endNum.Append(item);
  38.             }
  39.             Console.WriteLine(endingNums(endNum.ToString(), 0));
  40.         }
  41.         else
  42.         {
  43.             number = (short)(Math.Abs(number) - 1);
  44.             List<short> NumInBin = DecToBin(number);
  45.             for (int i = 0; i < NumInBin.Count; i++)
  46.             {
  47.                 if (NumInBin[i] == 0)
  48.                 {
  49.                     endNum.Append(1);
  50.                 }
  51.                 else
  52.                 {
  53.                     endNum.Append(0);
  54.                 }
  55.             }
  56.             Console.WriteLine(endingNums(endNum.ToString(), 1));
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement