简体   繁体   中英

How do I convert a double to a proprietary floating point format in C#?

I have a 20 bit proprietary floating point format defined as:

Bits: 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
Use:   s  e  e  e  e  e  m  m  m  m  m  m  m  m  m  m  m  m  m  m 

Where 
s = sign, (1=negative, 0=positive)
e = exponent, (10^0 to 10^31)
m = mantissa, (2^0 to 2^14-1, 0 to 16383)

This bit allocation gives a range of values from -16383 X 10^31 to +16383 X 10^31.

Now if I have a double value (or preferable decimal) in C#, how do I convert this number to this proprietary floating point format? There is a decimal constructor - Decimal(int lo, int mid, int hi, bool isNegative, byte scale) - that can help me to convert this format to a decimal but not the other way round. Over to you...

Here is one way to do the conversion, (probably not optimal):

public static class Converter
{
    private const int cSignBit = 0x80000; // 1 bit
    private const int cExponentBits = 0x7C000; // 5 bits
    private const int cMaxExponent = 0x1F; // 5 bits
    private const int cMantissaBits = 0x03FFF; // 14 bits
    private const double cExponentBase = 10;
    private const int cScale = 100000;

    public static int DoubleToAmount(double aValue)
    {
        // Get the sign
        bool lNegative = (aValue < 0);

        // Get the absolute value with scaling
        double lValue = Math.Abs(aValue) * cScale;

        // Now keep dividing by 10 to get the exponent value
        int lExponent = 0;
        while (Math.Ceiling(lValue) > cMantissaBits)
        {
            lExponent++;
            if (lExponent > cMaxExponent)
                throw new ArgumentOutOfRangeException("Cannot convert amount", (Exception)null);
            lValue = lValue / (double)cExponentBase;
        }

        // The result that is left rounded up is the mantissa
        int lMantissa = (int)Math.Ceiling(lValue);

        // Now we pack it into the specified format
        int lAmount = (lNegative ? cSignBit : 0) + lExponent * (cMantissaBits + 1) + lMantissa;

        // And return the result
        return lAmount;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM