2017-07-16 391 views
0

我需要將8字節長的十六進制數字轉換爲C#中的浮點數。 例如:在C#中將十六進制轉換爲IEEE 754浮點數

40300000億應該是16.0

C0622EB860000000應該是-14.46

40900000億應該是1024.0

我發現這個代碼,似乎工作,但它不會將對於大於10且小於-10的數字,正確指出 。例如, -14.46顯示爲-1.4546。代碼有什麼問題?

const string formatter = "{0,20}{1,27:E16}"; 

// Reinterpret the long argument as a double. 
public static void LongBitsToDouble(long argument) 
{ 
    double doubleValue; 
    doubleValue = BitConverter.Int64BitsToDouble(argument); 

    // Display the argument in hexadecimal. 
    Console.WriteLine(formatter, String.Format("0x{0:X16}", argument), 
    doubleValue); 
} 

public static void Main() 
{ 
    Console.WriteLine("This example of the BitConverter.Int64BitsToDouble(" 
    +"long) \nmethod generates the following output.\n"); 

    Console.WriteLine(formatter, "long argument","double value"); 
    Console.WriteLine("-------------"); 

    // Convert long values and display the results. 

    LongBitsToDouble(unchecked((long)0x4030000000000000)); //16.0 
    LongBitsToDouble(unchecked((long)0xC0622EB860000000)); //-14.46 


    Console.ReadKey(); 
} 
+1

代碼沒有問題。它也打印出指數,例如:E + 008。例如,10.0可以打印爲1.0E + 001 – Deolus

+0

如果您不想指數部分,請將其從'formatter'中移除。 IE:改爲「{0,20} {1,27}」;' – Deolus

+0

謝謝Deolus!這樣可行!我會投票你的答案,但我看不出如何。 – Marian

回答

0

請嘗試以下,第二個數字的小數點是錯誤的。我扭轉了字節。 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<List<byte>> inputs = new List<List<byte>>() { 
       new List<byte>() {0x40, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 
       new List<byte>() {0xC0, 0x62, 0x2E, 0xB8, 0x60, 0x00, 0x00, 0x00}, 
       new List<byte>() {0x40, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 
     }; 
      foreach (List<byte> input in inputs) 
      { 
       input.Reverse(); 
       Console.WriteLine(BitConverter.ToDouble(input.ToArray(),0)); 
      } 
      Console.ReadLine(); 
     } 
    } 
} 
+0

謝謝你的代碼。它也很好用! – Marian

相關問題