2 * Shamelessly lifted from Beej's Guide to Network Programming, found here:
4 * http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#serialization
6 * Below code was granted to the public domain.
11 uint64_t pack754(long double f, unsigned bits, unsigned expbits)
15 long long sign, exp, significand;
16 unsigned significandbits = bits - expbits - 1; // -1 for sign bit
18 // get this special case out of the way
22 // check sign and begin normalization
31 // get the normalized form of f and track the exponent
33 while (fnorm >= 2.0) {
43 // calculate the binary form (non-float) of the significand data
44 significand = fnorm * ((1LL << significandbits) + 0.5f);
46 // get the biased exponent
47 exp = shift + ((1 << (expbits - 1)) - 1); // shift + bias
49 // return the final answer
50 return (sign << (bits - 1)) | (exp << (bits-expbits - 1)) | significand;
53 long double unpack754(uint64_t i, unsigned bits, unsigned expbits)
58 unsigned significandbits = bits - expbits - 1; // -1 for sign bit
63 // pull the significand
64 result = (i & ((1LL << significandbits) - 1)); // mask
65 result /= (1LL << significandbits); // convert back to float
66 result += 1.0f; // add the one back on
68 // deal with the exponent
69 bias = (1 << (expbits - 1)) - 1;
70 shift = ((i >> significandbits) & ((1LL << expbits) - 1)) - bias;
81 result *= (i >> (bits - 1)) & 1 ? -1.0 : 1.0;