如何在C#中将double转换为专有浮点格式?

时间:2014-09-09 13:57:17

标签: c# floating-point type-conversion

我有一个20位专有浮点格式定义为:

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)

此位分配给出-16383 X 10 ^ 31至+16383 X 10 ^ 31的值范围。

现在,如果我在C#中有一个double值(或者更好的十进制),我该如何将此数字转换为此专有浮点格式?有一个小数构造函数 - Decimal(int lo, int mid, int hi, bool isNegative, byte scale) - 可以帮助我将这种格式转换为小数而不是相反。给你...

1 个答案:

答案 0 :(得分:0)

这是进行转换的一种方法,(可能不是最佳的):

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