ellapt

T10.9.FloatBinRepresent

Jan 22nd, 2013
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.66 KB | None | 0 0
  1. using System;
  2.  
  3. class FloatBinRepresent
  4. {
  5.  
  6.     // Print hexadecimal in binary format
  7.  
  8.     static void PrintBinary(int hexDecNumber, string formatter)
  9.     {
  10.         int binNumber = 0;
  11.         int temp = hexDecNumber;
  12.         byte position = 0;
  13.         string printStr = "";
  14.         do
  15.         {
  16.             int bitSet = temp & 1;
  17.             binNumber = (bitSet << position) | binNumber;
  18.             temp = temp >> 1;
  19.             position += 1;
  20.             printStr = bitSet + printStr;
  21.         } while (temp != 0);
  22.         for (int k = 0; k < 8 - position; k++)
  23.         {
  24.             printStr = "0" + printStr;
  25.         }
  26.         Console.Write(formatter, printStr);
  27.     }
  28.  
  29.     static void Main( )
  30.     {
  31.         Console.WriteLine("Show internal binary representation of given float number in IEEE 754 format\n");
  32.         string formatter;
  33.  
  34.         float floatNumber=-27.25f;
  35.  
  36.         byte[] byteArray = BitConverter.GetBytes(floatNumber);
  37.  
  38.         int mantissa = byteArray[2];
  39.         mantissa &= 0x7f;
  40.         mantissa <<= 16;
  41.         mantissa |= (byteArray[1] << 8);
  42.         mantissa |= byteArray[0];
  43.  
  44.         int exponent = byteArray[2] >> 7;
  45.         exponent=exponent|((byteArray[3]&0x7f)<<1);
  46.         int sign = byteArray[3]>>7;
  47.  
  48.         Console.WriteLine("{0}{1,10}{2,18}{3,25}\n", "float number", "sign", "exponent", "mantissa");
  49.         Console.Write("{0}", floatNumber);
  50.  
  51.         Console.Write("{0,14}",sign); ;
  52.  
  53.         formatter = "{0,20:D}";
  54.         PrintBinary(exponent, formatter);
  55.        
  56.         formatter = "{0,36:D}";
  57.         PrintBinary(mantissa, formatter);
  58.  
  59.         Console.WriteLine();
  60.         Console.WriteLine();
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment