简体   繁体   English

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

[英]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: 我有一种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)

This bit allocation gives a range of values from -16383 X 10^31 to +16383 X 10^31. 该位分配给出了从-16383 X 10 ^ 31到+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? 现在,如果我在C#中有一个双精度值(最好是十进制),如何将这个数字转换为这种专有的浮点格式? 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. 有一个十进制构造函数Decimal(int lo, int mid, int hi, bool isNegative, byte scale) -可以帮助我将这种格式转换为十进制,但不能Decimal(int lo, int mid, int hi, bool isNegative, byte scale) 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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