+ size_t fraction_leading_zeroes = max_bits;
+ for (size_t i = 0; i < max_bits; ++i)
+ {
+ x *= 2;
+ if (x >= 1.0)
+ {
+ if (fraction_leading_zeroes > i)
+ fraction_leading_zeroes = i;
+ x -= 1;
+ fraction |= (1LL << (max_bits-1-i));
+ }
+ if (x <= 0.0)
+ break;
+ }
+
+ uint64_t mantissa = 0LL;
+ int64_t biased_exponent = 0LL;
+
+ size_t integer_leading_zeroes = 0;
+ for (integer_leading_zeroes = 0; integer_leading_zeroes < max_bits; ++integer_leading_zeroes)
+ {
+ if ((integer >> (max_bits-1-integer_leading_zeroes)) & 1LL)
+ break;
+ }
+
+ // 0|011 11|00 0000 0001
+ // 0001
+ // 0000 0000 0100
+ // 10000 0000 0100
+ if (integer != 0)
+ {
+ mantissa = (integer << (integer_leading_zeroes));
+ mantissa |= (fraction >> (max_bits - integer_leading_zeroes));
+ }
+ else
+ {
+ mantissa = (fraction << (fraction_leading_zeroes));
+ }
+ //Debug("Mantissa with fraction %.16lx (%.16lx >><>?<< %lu)", mantissa, fraction, fraction_leading_zeroes);
+ mantissa = (mantissa >> (max_bits - PREC - 1));
+ //Debug("Mantissa is %.16lx (%.16lx . %.16lx)", mantissa, fraction, integer);
+ biased_exponent = (integer != 0) ? (max_bits - integer_leading_zeroes) : (-fraction_leading_zeroes);
+ if (biased_exponent < -(1LL << (EMAX-1))+1)
+ {
+ //Debug("Denormalising for glory or death! %li , %li", biased_exponent, -(1LL << (EMAX-1)) - biased_exponent + 1);
+ mantissa = mantissa >> (-(1LL << (EMAX-1)) - biased_exponent + 1);
+ biased_exponent = -(1LL << (EMAX-1))+1;
+ }
+ //Debug("Biased exponent is %li", biased_exponent);
+
+ // If the unbiased exponent would be non-zero, the IEEE has the leading 1 as implied; remove it and decrease exponent to compensate
+ if (biased_exponent != -(1LL << (EMAX-1))+1)
+ {
+ //Debug("Implied 1 in mantissa %.16lx", mantissa);
+ mantissa &= ~(1LL << (PREC));
+ //Debug("Implied 1 in mantissa %.16lx", mantissa);
+ biased_exponent -= 1;
+ }
+ else
+ {
+ mantissa >>= 1;
+ }
+ //Debug("%.16lx", mantissa);
+
+ uint64_t exponent = (uint64_t)(biased_exponent + (1LL << (EMAX-1))-1); // offset the exponent
+
+ // Debug
+ /*
+ Real M = (exponent != 0);
+ for (size_t i = 1; i < PREC; ++i)
+ {
+ if ((mantissa >> PREC-i) & 1)
+ M += Real(1) / powl(BASE, i);
+ }
+
+ Debug("Exponent: %lx %lu -> %li", exponent, exponent, biased_exponent);
+ Debug("Mantissa: %lx -> %f", mantissa, Float(M));
+ Debug("Both: %lx", mantissa | (exponent << (PREC)));
+ */
+ // Now copy the bits in
+ BitsFromRepr<EMAX, PREC, BASE>(sign, mantissa, exponent, data);