Search code examples
c#hexieee-754

Convert hex to IEEE 754 floating point in C#


I need to convert 8byte-long hex numbers to floating point in C#. For example :

4030000000000000 should be 16.0

C0622EB860000000 should be -14.46

4090000000000000 should be 1024.0

I have found this code that seems to work, but it doesn't place the point correctly for numbers larger than 10 and smaller than -10. For exemple, -14.46 is displayed as -1.4546. What is wrong with the code?

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

Solution

  • Try following, 2nd number decimal place is wrong. I reversed the bytes. :

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