2017-07-16 390 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

相关问题