Convert Hex to Double

前端 未结 4 1706
小蘑菇
小蘑菇 2020-12-11 17:50

how do you set specific bits for a double?

For an int I\'d do something like this:

public static int Value { get { return 0xfff8; } }
相关标签:
4条回答
  • 2020-12-11 17:59

    Look at the BitConverter class or go unsafe.

    Unsafe example (untested):

    public unsafe double FromLong(long x)
    {
      return *((double*)&x);
    }
    

    BitConverter example:

    double d = BitConverter.Int64BitsToDouble(0xdeadbeef);
    

    http://msdn2.microsoft.com/en-us/library/system.bitconverter.int64bitstodouble

    0 讨论(0)
  • 2020-12-11 18:16

    I just looked into the topic of converting a Hex string of a Double Value back into a Double Value. I found some usefull sites. This Site shows how to calculate a double value: https://gregstoll.dyndns.org/~gregstoll/floattohex/ This shows how decimal point fractals are calulated(binary excample) https://www.geeksforgeeks.org/convert-binary-fraction-decimal/

    My example input value is 40C688C000000000, resulting in 11537.5 Important are the first 3 Hex Values, because they are the exponent used for the Double Value. The Amount of Hex Values after this doesn't really matter.

    This is the simple Code I created from this Information:

    public static double DoubleFromHex(string hex)
    {
        int exponent;
        double result;
        string doubleexponenthex = hex.Substring(0, 3);
        string doublemantissahex = hex.Substring(3);
        double mantissavalue = 1; //yes this is how it works
    
        for (int i = 0; i < doublemantissahex.Length; i++)
        {
            int hexsignvalue = Convert.ToInt32(doublemantissahex.Substring(i, 1),16); //Convert ,16 Converts from Hex
            mantissavalue += hexsignvalue * (1 / Math.Pow(16, i+1));
        }
    
        exponent = Convert.ToInt32(doubleexponenthex, 16);
        exponent = exponent - 1023;  //just how it works
    
        result = Math.Pow(2, exponent) * mantissavalue;
        return result;
    }
    
    0 讨论(0)
  • 2020-12-11 18:17
    byte bTemp = Convert.ToByte(hexValueInString, 16);
    double doubleTemp = Convert.ToDouble(bTemp);
    

    I'm using .NET 4.0

    0 讨论(0)
  • 2020-12-11 18:22

    Let's assume you have the following string 0x4007B425F202107B which represents double value.

    To convert it to double (IEEE754 Double precision 64-bit), you need to use the following code:

    var hex = "0x4007B425F202107B";
    var int64Val = Convert.ToInt64(hex, 16);
    var doubleVal = BitConverter.Int64BitsToDouble(int64Val);
    

    Online converter from hex to double.

    0 讨论(0)
提交回复
热议问题