Is there any straightforward way to get the mantissa and exponent from a double in c# (or .NET in general)?
I found this example using Google, but I’m not sure how robust it would be. Could the binary representation for a double change in some future version of the framework, etc?
The other alternative I found was to use System.Decimal instead of double and use the Decimal.GetBits() method to extract them.
Any suggestions?
The binary format shouldn’t change – it would certainly be a breaking change to existing specifications. It’s defined to be in IEEE754 / IEC 60559:1989 format, as Jimmy said. (C# 3.0 language spec section 1.3; ECMA 335 section 8.2.2). The code in DoubleConverter should be fine and robust.
For the sake of future reference, the relevant bit of the code in the example is:
The comments made sense to me at the time, but I’m sure I’d have to think for a while about them now. After the very first part you’ve got the ‘raw’ exponent and mantissa – the rest of the code just helps to treat them in a simpler fashion.