Advertisement
ScorpS

IEEE 754 Format

Jan 20th, 2013
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1.  
  2. //* Write a program that shows the internal binary representation of given 32-bit signed
  3. //floating-point number in IEEE 754 format (the C# type float). Example: -27,25  sign = 1,
  4. //exponent = 10000011, mantissa = 10110100000000000000000.
  5.  
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11.  
  12.  
  13. class IEEE754Format9
  14. {
  15.     static void Main()
  16.     {
  17.         float number = float.Parse(Console.ReadLine());
  18.         long convertBitsOfNumber = BitConverter.DoubleToInt64Bits(number);
  19.         long mask = 1;
  20.         long sign = 0;
  21.         string binaryRepresentation = "";
  22.         string exponent;
  23.         string mantisa;
  24.  
  25.         // check for the sign
  26.         sign = ((convertBitsOfNumber >> 63) & mask);
  27.  
  28.         // just in case make the bit which show the sign to be 0 in that way the number will be positive with sure
  29.         convertBitsOfNumber = (convertBitsOfNumber & (~(mask << 63)));
  30.  
  31.         // take every bit from the number
  32.         while (convertBitsOfNumber != 0)
  33.         {
  34.             binaryRepresentation = (convertBitsOfNumber % 2) + binaryRepresentation;
  35.             convertBitsOfNumber /= 2;
  36.         }
  37.  
  38.         if (number > -2.0f && number < 2.0f)
  39.         {
  40.             exponent = "0";
  41.  
  42.             exponent += binaryRepresentation.Substring(3, 7);
  43.  
  44.             mantisa = binaryRepresentation.Substring(10, 23);
  45.         }
  46.         else
  47.         {
  48.             exponent = binaryRepresentation.Substring(0, 1);
  49.  
  50.             // here we take from this position because we used 64 bits number and this 3 digits are no necessary for 32 bits number
  51.             exponent += binaryRepresentation.Substring(4, 7);
  52.  
  53.             mantisa = binaryRepresentation.Substring(11, 23);
  54.         }
  55.  
  56.         Console.Write(sign + " ");
  57.         Console.Write(exponent + " ");
  58.         Console.WriteLine(mantisa);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement