2017-07-16 30 views
0

C#で8バイト長の16進数を浮動小数点数に変換する必要があります。たとえば :C#で16進数をIEEE 754浮動小数点に変換

4030000000000000は16.0

C0622EB860000000は-14.46

4090000000000000する必要がありますする必要があります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

コードに問題はありません。それは指数ie:E + 008も表示します。例えば、10.0は1.0E + 001として印刷することができます。 – Deolus

+0

指数部が不要な場合は、それを 'formatter'から削除します。 IE: '{0,20} {1,27} 'に変更してください; – Deolus

+0

Deolusに感謝!それは動作します!私はあなたの答えに投票しただろうが、私はどのように見ることができません。 – Marian

答えて

0

小数点第2位は小数点以下を入力してください。私はバイトを逆転させた。 :

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

関連する問題