Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How to convert a double number to hex againg

hex to long .
Posted
Updated 2-Mar-10 22:12pm
v2

Hex is a system of representation, not a number. You can use a format specifier on a number to turn it into a hex string, via the ToString method. I believe it is x. You may be able to use a format specifier in long.TryParse or long.Parse to get it back to a number.
 
Share this answer
 
v2
I think you should first convert the double to a byte array, see the example in the "BitConverter.GetBytes Method" documentation.
 
Share this answer
 
C#
internal static string DoubleToHex(double value, int maxDecimals)
{
    string result = string.Empty;
    if (value < 0)
    {
        result += "-";
        value = -value;
    }
    if (value > ulong.MaxValue)
    {
        result += double.PositiveInfinity.ToString();
        return result;
    }
    ulong trunc = (ulong)value;
    result += trunc.ToString("X");
    value -= trunc;
    if (value == 0)
    {
        return result;
    }
    result += ".";
    byte hexdigit;
    while ((value != 0) && (maxDecimals != 0))
    {
        value *= 16;
        hexdigit = (byte)value;
        result += hexdigit.ToString("X");
        value -= hexdigit;
        maxDecimals--;
    }
    return result;
}

internal static ulong HexToUInt64(string hex)
{
    ulong result;
    if (ulong.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result))
    {
        return result;
    }
    throw new ArgumentException("Cannot parse hex string.", "hex");
}
 
Share this answer
 
For example when i convert 0.32456 to hex it is giving error as invalid format specified..
pls help
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900