Convert Hex to Double

前端 未结 4 1709
小蘑菇
小蘑菇 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 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;
    }
    

提交回复
热议问题