Alex Rivera | Logout

Can C#/.net parse exponential hex encoded floating point numbers from strings?

Asked 2012-11-15T00:59:35.710
8

C++, Java all include the [-]0xh.hhhhp+/-d format in the syntax of the language, other languages like python and C99 have library support for parsing these strings (float.fromhex, scanf).

I have not, yet, found a way to parse this exact hex encoded exponential format in C# or using the .NET libraries.

Is there a good way to handle this, or a decent alternative encoding? (decimal encoding is not exact).

Example strings: 0x1p-8 -0xfe8p-12

Thank you

Edit
Report

1 Answer

2

Unfortunately, I don't know of any method built-in to .NET that compares to Python's float.fromhex(). So I suppose the only thing you can do is roll your own .fromhex() in C#. This task can range in difficulty from "Somewhat Easy" to "Very Difficult" depending on how complete and how optimized you'd like your solution to be.

Officially, the IEEE 754 spec allows for decimals within the hexadecimal coefficient (ie. 0xf.e8p-12) which adds a layer of complexity for us since (much to my frustration) .NET also does not support Double.Parse() for hexadecimal strings.

If you can constrain the problem to examples like you've provided where you only have integers as the coefficient, you can use the following solution using string operations:

public static double Parsed(string hexVal)
{
    int index = 0;
    int sign = 1;
    double exponent = 0d;

    //Check sign
    if (hexVal[index] == '-')
    {
        sign = -1;
        index++;
    }
    else if (hexVal[index] == '+')
        index++;
    //consume 0x
    if (hexVal[index] == '0')
    {
        if (hexVal[index+1] == 'x' || hexVal[index+1] == 'X')
            index += 2;
    }

    int coeff_start = index;
    int coeff_end = hexVal.Length - coeff_start;

    //Check for exponent
    int p_index = hexVal.IndexOfAny(new char[] { 'p', 'P' });
    if (p_index == 0)
        throw new FormatException("No Coefficient");
    else if (p_index > -1)
    {
        coeff_end = p_index - index;
        int exp_start = p_index + 1;
        int exp_end = hexVal.Length;
        exponent = Convert.ToDouble(hexVal.Substring(exp_start, exp_end - (exp_start)));
    }

    var coeff = (double)(Int32.Parse(hexVal.Substring(coeff_start, coeff_end), NumberStyles.AllowHexSpecifier));
    var result = sign * (coeff * Ma
answered 2012-11-23T23:38:48.140

Your Answer