util: add getbefloat64

As far as I can tell, this is wrong. double's format isn't strictly
specified in the C standard, but the wikipedia article implies that
platforms implementing optional Annex F "IEC 60559 floating-point
arithmetic" will work correctly.

My local C experts believe doing *((double *) &t) is a strict aliasing
violation, and that using a union is also one. Doing memcpy appears to
be the least-undefined behavior possible.
This commit is contained in:
Augie Fackler 2015-02-03 13:17:21 -05:00
parent 8ef7d1d411
commit 78ce05f424

View File

@ -196,4 +196,17 @@ static inline void putbe32(uint32_t x, char *c)
c[3] = (x) & 0xff;
}
static inline double getbefloat64(const char *c)
{
const unsigned char *d = (const unsigned char *)c;
double ret;
int i;
uint64_t t = 0;
for (i = 0; i < 8; i++) {
t = (t<<8) + d[i];
}
memcpy(&ret, &t, sizeof(t));
return ret;
}
#endif /* _HG_UTIL_H_ */