Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace _09.BinaryRepresentationOfFloat
- {
- class BinaryRepresentationOfFloat
- {
- private static char SignDefine(ref float number)
- {
- char sign;
- if (number >= 0)
- {
- sign = '0';
- }
- else
- {
- sign = '1';
- }
- number = Math.Abs(number);
- return sign;
- }
- static string DecimalToByteBinary(int decimalNumber)
- {
- string result = "";
- while (decimalNumber > 0)
- {
- result = (decimalNumber % 2).ToString() + result;
- decimalNumber /= 2;
- }
- string addZeros = new string('0', 8 - result.Length);
- result = addZeros + result;
- return result;
- }
- private static string ExponentDefine(ref float number)
- {
- string exponent;
- int decExponent = 0;
- while ((number < 1 || number > 2) && number != 0)
- {
- if (number < 1)
- {
- number *= 2;
- decExponent--;
- }
- else
- {
- number /= 2;
- decExponent++;
- }
- }
- number--;
- exponent = DecimalToByteBinary(127 + decExponent);
- return exponent;
- }
- private static string MantissaDefine(float number)
- {
- float bitValue = 0.5f;
- string mantissa = "";
- for (int i = 0; i < 23; i++)
- {
- if (number - bitValue >= 0)
- {
- mantissa += '1';
- number = number - bitValue;
- }
- else
- {
- mantissa += '0';
- }
- bitValue /= 2;
- }
- return mantissa;
- }
- static void FloatInBinary(float number, out char sign, out string exponent, out string mantissa)
- {
- sign = SignDefine(ref number);
- exponent = ExponentDefine(ref number);
- mantissa = MantissaDefine(number);
- }
- static void Main(string[] args)
- {
- float number = -27.25f;
- Console.WriteLine("Number: {0}",number);
- char sign;
- string exponent;
- string mantissa;
- FloatInBinary(number, out sign, out exponent, out mantissa);
- Console.WriteLine("Sign: {0}",sign);
- Console.WriteLine("Exponent: {0}",exponent);
- Console.WriteLine("Mantissa: {0}",mantissa);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement