Advertisement
Asinka

BynaryRepOfFloating-point

Jan 21st, 2013
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System;
  2.  
  3.  
  4.  
  5. class BynaryRepOfFloatingPoint
  6. {
  7.     static void Main()
  8.     {
  9.         float number = float.Parse(Console.ReadLine());
  10.         int sign = 0;
  11.  
  12.         //Difining and printing "Sign" of the number
  13.         if (number < 0) { sign = 1; number = -1 * number;  }
  14.  
  15.         Console.WriteLine("Sign = {0}", sign);
  16.  
  17.  
  18.  
  19.         //Difining and printing "Exponent" of the number
  20.         Console.Write("Exponent = ");
  21.  
  22.         int exponent = 0;
  23.         int i = 0;
  24.  
  25.  
  26.         for (i = 0; i <= number; i++)   //Count Math.Squre of the number, wihtout loosing of data
  27.         {
  28.             exponent = (int)Math.Pow(2, i);
  29.             if (exponent >= number) { break; }
  30.         }
  31.  
  32.         exponent = (i - 1) + 127;   //Count "Exponent" ot the number. Exponent(X): x - 124 = Math.Squre of the number
  33.  
  34.         for (int j = 7; j >= 0; j--)    //Printing the bynary representation of the Exponent(X)
  35.         {
  36.             int multiple = (int)Math.Pow(2, j);
  37.             int digit = (int)(exponent / multiple);
  38.             exponent = exponent % multiple;
  39.  
  40.             Console.Write(digit);
  41.         }
  42.         Console.WriteLine();
  43.  
  44.         //Difining and printing "Mantissa" of the number
  45.         Console.Write("Mantissa = ");
  46.  
  47.         double mantissa = (double)number / Math.Pow(2, i-1);
  48.         mantissa = mantissa - 1;
  49.        
  50.         for (i = 1; i < 24; i++)
  51.         {
  52.             double multiple = Math.Pow(2, -i);
  53.             if (mantissa - multiple >= 0)
  54.             {
  55.                 Console.Write(1);
  56.                 mantissa = mantissa - multiple;
  57.             }
  58.             else
  59.             {
  60.                 Console.Write(0);
  61.             }
  62.         }
  63.         Console.WriteLine();        
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement