开发者

Convert Hex to Double

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

What should I do for double?

public static double Value { get { return 0xfff8; } }

I'm a bit concerned that I may get an 开发者_运维技巧implicit conversion from an int representation of 0xfff8 to the double floating point representation. However, I really want that 0xfff8 bit pattern regardless of the type.


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


byte bTemp = Convert.ToByte(hexValueInString, 16);
double doubleTemp = Convert.ToDouble(bTemp);

I'm using .NET 4.0


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜