Advertisement
sashomaga

Convert 16 bit signed integer

Jan 18th, 2013
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. //Write a program that shows the binary representation of given 16-bit signed integer number
  4. class SignedShortToBinary
  5. {
  6.     static void Main()
  7.     {
  8.         Console.WriteLine("Enter 16-bit signed integer number: ");
  9.         short convert = short.Parse(Console.ReadLine());
  10.        
  11.         StringBuilder builder = new StringBuilder();
  12.         string result = "";
  13.  
  14.         if (convert < 0)
  15.         {      
  16.             short temp;
  17.             temp = ((short)(Math.Pow(2, 15) - convert));
  18.  
  19.             for (int i = 0; i < 14; i++)
  20.             {
  21.                 if ((temp & 1) == 1)
  22.                 {
  23.                     builder.Insert(0, 1);
  24.                 }
  25.                 else
  26.                 {
  27.                     builder.Insert(0, 0);
  28.                 }
  29.                 temp /= 2;
  30.             }
  31.             builder.Insert(0, 1);
  32.             result = builder.ToString();
  33.         }
  34.         else
  35.         {
  36.             while (convert > 0)
  37.             {
  38.                 if ((convert & 1) == 1)
  39.                 {
  40.                     builder.Insert(0, 1);
  41.                 }
  42.                 else
  43.                 {
  44.                     builder.Insert(0, 0);
  45.                 }
  46.                 convert /= 2;
  47.             }
  48.             result = builder.ToString();
  49.         }
  50.         Console.WriteLine("Binary representation: \n{0}",result);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement