Extracting mantissa and exponent from double in C #

Is there an easy way to get the mantissa and exponent from double in C # (or .NET in general)?

I found this example using Google, but I'm not sure how fast it is. Can a binary representation for double change in some future version of the framework, etc.

Another alternative I found was to use System.Decimal instead of double and use the Decimal.GetBits () method to retrieve them.

Any suggestions?

+24
floating-point c #
Dec 23 '08 at 20:26
source share
2 answers

The binary format should not change - this, of course, will be a violation of existing specifications. It is defined in the IEEE754 / IEC 60559: 1989 format, as Jimmy said. (Section 1.3 of the C # 3.0 Language Specifications, Section 8.2.2 of ECMA 335). The code in DoubleConverter must be accurate and reliable.

For future reference, the corresponding code bit in the example:

public static string ToExactString (double d) { … // Translate the double into sign, exponent and mantissa. long bits = BitConverter.DoubleToInt64Bits(d); // Note that the shift is sign-extended, hence the test against -1 not 1 bool negative = (bits & (1L << 63)) != 0; int exponent = (int) ((bits >> 52) & 0x7ffL); long mantissa = bits & 0xfffffffffffffL; // Subnormal numbers; exponent is effectively one higher, // but there no extra normalisation bit in the mantissa if (exponent==0) { exponent++; } // Normal numbers; leave exponent as it is but add extra // bit to the front of the mantissa else { mantissa = mantissa | (1L << 52); } // Bias the exponent. It actually biased by 1023, but we're // treating the mantissa as m.0 rather than 0.m, so we need // to subtract another 52 from it. exponent -= 1075; if (mantissa == 0) { return negative ? "-0" : "0"; } /* Normalize */ while((mantissa & 1) == 0) { /* ie, Mantissa is even */ mantissa >>= 1; exponent++; } … } 

I liked the comments at the time, but I'm sure I will have to think about it now. After the first part, you have a raw exponent and a mantissa - the rest of the code just helps to treat them more simply.

+27
Dec 23 '08 at 21:03
source share

Presentation is an IEEE standard and should not be changed.

https://msdn.microsoft.com/en-us/library/system.double(v = vs .110) .aspx

The Double type complies with IEC 60559: 1989 (IEEE 754) for binary floating point arithmetic.

EDIT: The reason the decimal code has getBits, and double is not that the decimal point stores significant digits. 3.0000m == 3.00m, but the exponents / mantissas are actually different. I think floats / doubles are uniquely represented.

+1
Dec 23 '08 at 20:30
source share



All Articles