在 C# 中将十六进制转换为 IEEE 754 浮点数

Convert hex to IEEE 754 floating point in C#

我需要在 C# 中将 8 字节长的十六进制数转换为浮点数。 例如:

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();
}

尝试以下,小数点后第二位错误。我颠倒了字节。 :

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();
        }
    }
}