fork(1) download
  1. using System;
  2.  
  3. class DoubleInfo
  4. {
  5. public long Mantissa;
  6. public int Exponent;
  7. public bool IsNegative;
  8.  
  9. public override string ToString()
  10. {
  11. return
  12. $"Mantissa: {Mantissa:X8}, Exponent: {Exponent}, " +
  13. $"Sign: {(IsNegative ? '-' : '+')}";
  14. }
  15. }
  16.  
  17. class Program
  18. {
  19. static DoubleInfo ExtractInfo(double d)
  20. {
  21. if (double.IsInfinity(d) || double.IsNaN(d))
  22. return null;
  23.  
  24. var result = new DoubleInfo();
  25. long bits = BitConverter.DoubleToInt64Bits(d);
  26.  
  27. result.IsNegative = bits < 0;
  28. result.Exponent = (int) ((bits >> 52) & 0x7ffL);
  29. result.Mantissa = bits & 0xfffffffffffffL;
  30.  
  31. if (result.Exponent == 0) // субнормальные числа
  32. result.Exponent++;
  33. else // нормальные числа, добавляем ведущий бит
  34. result.Mantissa = result.Mantissa | (1L << 52);
  35.  
  36. result.Exponent -= 1023; // экспонента сдвинута на 1023
  37. return result;
  38. }
  39.  
  40. static void Main(string[] args)
  41. {
  42. double d1 = 2.1;
  43. double d2 = 2;
  44. double diff = d1 - d2;
  45. Console.WriteLine($"d1 : {ExtractInfo(d1)}");
  46. Console.WriteLine($"d2 : {ExtractInfo(d2)}");
  47. Console.WriteLine($"d1 - d2: {ExtractInfo(diff)}");
  48. }
  49. }
Success #stdin #stdout 0.04s 23920KB
stdin
Standard input is empty
stdout
d1     : Mantissa: 10CCCCCCCCCCCD, Exponent: 1, Sign: +
d2     : Mantissa: 10000000000000, Exponent: 1, Sign: +
d1 - d2: Mantissa: 199999999999A0, Exponent: -4, Sign: +