Advertisement
ScorpS

Show Bits From Number Of Type Short

Jan 20th, 2013
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  1.  
  2. //Write a program that shows the binary representation of given 16-bit signed integer number (the C# type short).
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10.  
  11. class ShowBitsFromNumberOfTypeShort
  12. {
  13.     static void Main()
  14.     {
  15.         short number = short.Parse(Console.ReadLine());
  16.         short mask = 1;
  17.         short sign = 0;
  18.         string binaryRepresentation = "";
  19.  
  20.         // check for the sign
  21.         sign = (short)((number >> 15) & mask);
  22.  
  23.         // just in case make the bit which show the sign to be 0 in that way the number will be positive with sure
  24.         number = (short)(number & (~(mask << 15)));
  25.  
  26.         // take every bit from the number
  27.         while (number != 0)
  28.         {
  29.             binaryRepresentation = (number % 2) + binaryRepresentation;
  30.             number /= 2;
  31.         }
  32.  
  33.         while (binaryRepresentation.Length < 15)
  34.         {
  35.             binaryRepresentation = "0" + binaryRepresentation;
  36.         }
  37.  
  38.         // here we add the sign if it is "-" it will be added 1, in other case will be added 0
  39.         binaryRepresentation = sign + binaryRepresentation;
  40.         Console.WriteLine(binaryRepresentation);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement