[英]How do I convert a double to a proprietary floating point format in C#?
我有一種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#中有一個雙精度值(最好是十進制),如何將這個數字轉換為這種專有的浮點格式? 有一個十進制構造函數Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
-可以幫助我將這種格式轉換為十進制,但不能Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
。 交給你...
這是進行轉換的一種方法(可能不是最佳方法):
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.