+ 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;
+
+ // Combine integer and fraction into mantissa
+ if (integer == 0)
+ {
+ //Debug("0. %lx (%d)", fraction, fraction_leading_zeroes);
+ // Mantissa must have leading '1'; shift to get leading 1, then shift back to mantissa position
+ mantissa = (fraction << fraction_leading_zeroes) >> (max_bits - PREC);
+ biased_exponent -= fraction_leading_zeroes;
+ // If the unbiased exponent would be negative use a denormalised number instead
+ if (biased_exponent < -(1LL << (EMAX-1))+1)
+ {
+ mantissa = mantissa >> (-(1LL << (EMAX-1))+1 - biased_exponent);
+ biased_exponent = -(1LL << (EMAX-1))+1;
+ }
+ }
+ else
+ {
+
+ 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;
+ }
+ //Debug("%.16lx . %.16lx (%li, %li)", integer,fraction, integer_leading_zeroes, fraction_leading_zeroes);
+
+ mantissa = (integer << (integer_leading_zeroes)); // shift integer part
+ mantissa |= (fraction >> (max_bits-integer_leading_zeroes)); // append the fraction after it
+ //Debug("%.16lx (%.16lx << %i)", mantissa, fraction, (fraction_leading_zeroes - max_bits + integer_leading_zeroes));
+ mantissa = mantissa >> (max_bits - PREC); // shift back to the mantissa position
+ biased_exponent = (max_bits - integer_leading_zeroes); // calculate 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)
+ {
+ mantissa &= ~(1LL << max_bits - PREC);
+ mantissa = mantissa << 1;
+ biased_exponent -= 1;
+ }
+
+ 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);