Advertisement
zlatkov

FloatToBinary

Jan 15th, 2013
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace FloatToBinary
  8. {
  9.     class FloatToBinary
  10.     {
  11.         static int GetLeftNibble(byte x)
  12.         {
  13.             return (x >> 4);
  14.         }
  15.  
  16.         static int GetRightNibble(byte x)
  17.         {
  18.             return (x & 15);
  19.         }
  20.  
  21.         static string NibbleToBinary(int x)
  22.         {
  23.             string result = "";
  24.             for (int i = 3; i >= 0; --i)
  25.             {
  26.                 result += (x >> i) & 1;
  27.             }
  28.  
  29.             return result;
  30.         }
  31.  
  32.         static string ConvertFloatToBinary(float floatNumber)
  33.         {
  34.             string result = "";
  35.             byte[] floatBytes = BitConverter.GetBytes(floatNumber);
  36.             for (int i = 3; i >= 0; --i)
  37.             {
  38.                 result += NibbleToBinary(GetLeftNibble(floatBytes[i]));
  39.                 result += NibbleToBinary(GetRightNibble(floatBytes[i]));
  40.             }
  41.  
  42.             return result;
  43.         }
  44.  
  45.         static void Main(string[] args)
  46.         {
  47.             float floatNumber = float.Parse(Console.ReadLine());
  48.  
  49.             string binaryNumber = ConvertFloatToBinary(floatNumber);
  50.  
  51.             Console.WriteLine("Binary representation: " + binaryNumber);
  52.             Console.WriteLine("Sign: " + binaryNumber[0]);
  53.             Console.WriteLine("Exponent: " + binaryNumber.Substring(1, 8));
  54.             Console.WriteLine("Mantissa: " + binaryNumber.Substring(9));
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement