I am new to #, could you tell me how to write a program so that it displays a complete solution for adding binary floating point numbers (full stop). Something very much was busy itself, but no result.

For example, I created a program:

using System; using System.Linq; using System.Text; namespace ConsoleTest { class Program { static char[] delim = new[] { '.', ',' }; static void Main(string[] args) { char[] allowedChars = new[] { '0', '1' }.Concat(delim).ToArray(); string[] data = new string[2]; for (int n = 0; n < 2; n++) { Console.Write("Введите число №{0} в двоичной системе счисления: ", n + 1); data[n] = Console.ReadLine(); bool hasDelim = false; for (int i = 0; i < data[n].Length; i++) { if (!allowedChars.Contains(data[n][i])) { Console.WriteLine("Ошибка. Неверные данные. Символ '{0}' не может присутствовать в числе в двоичной системе счисления.\nНажмите любую клавишу для выхода из программы.", data[n][i]); Console.ReadKey(); return; } if (delim.Contains(data[n][i])) if (!hasDelim) hasDelim = true; else { Console.WriteLine("Ошибка. В числе не может быть больше одного десятичного разделителя.\nНажмите любую клавишу для выхода из программы."); Console.ReadKey(); return; } } } Console.WriteLine("Данные верные"); Console.WriteLine("Сумма чисел: {0}", From10To2(GetValue(data[0]) + GetValue(data[1]))); Console.ReadKey(); } // из строки в десятичное число static double GetValue(string input) { input = input.Trim(delim); double retVal = 0; double pow = input.Split(delim)[0].Length - 1; for (int i = 0; i < input.Length; i++) if (delim.Contains(input[i])) continue; else retVal += Math.Pow(2, pow--) * Convert.ToDouble(input[i].ToString()); return retVal; } // Из double в двоичное число static string From10To2(double input) { string retval = ""; // Отделяем целую и дробную части string[] data = input.ToString().Split(delim); StringBuilder sb = new StringBuilder(); int a = Convert.ToInt32(data[0]); do // Запоминаем остаток от деления на 2 sb.Append(a % 2); // продолжаем деление, пока число больше 1 while ((a = a / 2) > 1); // запоминаем последнее число sb.Append(a); retval += String.Join("", sb.ToString().Reverse().ToArray()); sb.Clear(); // есть дробная часть if (data.Length > 1) { sb.Append("."); double d = input; d -= (int)d; while ((d = (d - (int)d) * 2) != 0) sb.Append((int)d); } return retval + sb.ToString(); } } } 

But how to show the change of the mantissa and order do not understand

PS After the prompt, I recorded the program so

  using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class DoubleInfo { public long Mantissa; public int Exponent; public bool IsNegative; public override string ToString() { return "Mantissa: {Mantissa:X8}, Exponent: {Exponent}, " + "Sign: {(IsNegative ? '-' : '+')}"; } } class Program { static DoubleInfo ExtractInfo(double d) { if (double.IsInfinity(d) || double.IsNaN(d)) return null; var result = new DoubleInfo(); long bits = BitConverter.DoubleToInt64Bits(d); result.IsNegative = bits < 0; result.Exponent = (int) ((bits >> 52) & 0x7ffL); result.Mantissa = bits & 0xfffffffffffffL; if (result.Exponent == 0) // субнормальные числа result.Exponent++; else // нормальные числа, добавляем ведущий бит result.Mantissa = result.Mantissa | (1L << 52); result.Exponent -= 1023; // экспонента сдвинута на 1023 return result; } static void Main(string[] args) { double d1 = 2.1; double d2 = 2; double diff = d1 - d2; Console.WriteLine("d1 : {ExtractInfo(d1)}"); Console.WriteLine("d2 : {ExtractInfo(d2)}"); Console.WriteLine("d1 - d2: {ExtractInfo(diff)}"); } } } 

but for some reason, this program does not give the result. Tell me what the error is

  • Is the complete solution a separate display of each changed bit? Better than a detailed description of a half-line of code ... - AivanF.
  • What do you mean by "complete solution ... (and further in the text)"? - Harry
  • How to change the mantissa and order - J.New
  • Usually they say "mantissa and exponent". By “order,” do you mean an exhibitor? - Kromster
  • Yes, exactly, just like that - J.New

1 answer 1

Apparently, you need something like this:

 class DoubleInfo { public long Mantissa; public int Exponent; public bool IsNegative; public override string ToString() { return $"Mantissa: {Mantissa:X8}, Exponent: {Exponent}, " + $"Sign: {(IsNegative ? '-' : '+')}"; } } class Program { static DoubleInfo ExtractInfo(double d) { if (double.IsInfinity(d) || double.IsNaN(d)) return null; var result = new DoubleInfo(); long bits = BitConverter.DoubleToInt64Bits(d); result.IsNegative = bits < 0; result.Exponent = (int) ((bits >> 52) & 0x7ffL); result.Mantissa = bits & 0xfffffffffffffL; if (result.Exponent == 0) // субнормальные числа result.Exponent++; else // нормальные числа, добавляем ведущий бит result.Mantissa = result.Mantissa | (1L << 52); result.Exponent -= 1023; // экспонента сдвинута на 1023 return result; } static void Main(string[] args) { double d1 = 2.1; double d2 = 2; double diff = d1 - d2; Console.WriteLine($"d1 : {ExtractInfo(d1)}"); Console.WriteLine($"d2 : {ExtractInfo(d2)}"); Console.WriteLine($"d1 - d2: {ExtractInfo(diff)}"); } } 

Issues:

 d1 : Mantissa: 10CCCCCCCCCCCD, Exponent: 1, Sign: + d2 : Mantissa: 10000000000000, Exponent: 1, Sign: + d1 - d2: Mantissa: 199999999999A0, Exponent: -4, Sign: + 

Read, understand.

  • I apologize, I may have misunderstood, but when I use this code, the program does not work at all. Please explain - J.New
  • that is, the syntax seems to be correct, but the program does not start - J.New
  • @ J.New: What program are you talking about? The one in my example or yours? - VladD
  • About that, by your example - J.New
  • @ J.New: Strange. Here it works on ideone: ideone.com/c7u8fp - VladD