Exemple #1
0
        /// <summary>Decompose an IEEE754 double into the mantissa and exponent</summary>
        public static void Decompose(this double x, out long mantissa, out int exponent, out int sign, bool raw = false)
        {
            //    Normal numbers: (-1)^sign x 2^(e - 1023) x 1.fraction
            // Subnormal numbers: (-1)^sign x 2^(1 - 1023) x 0.fraction

            // Translate the double into sign, exponent, and mantissa.
            var bits = unchecked ((ulong)BitConverter.DoubleToInt64Bits(x));

            sign     = bits.BitAt(63) != 0 ? -1 : +1;
            exponent = (int)Bit.Bits_(bits, 63, 52);
            mantissa = (long)Bit.Bits_(bits, 52, 0);
            if (raw)
            {
                return;
            }

            // Normal numbers: add the '1' to the front of the mantissa.
            if (exponent != 0)
            {
                mantissa |= 1L << 52;
            }
            else
            {
                exponent++;
            }

            // Bias the exponent
            exponent -= 1023;
        }