I have an unsigned long long
(or uint64_t
) value and want to convert it to a double
. The double shall have the same bit pattern as the long
value. This way I can set the bits of the double "by hand".
unsigned long long bits = 1ULL;
double result = /* some magic here */ bits;
I am looking for a way to do this.
The following uses a void pointer.
Beware of
union
andreinterpret_cast<double*>(&bits)
, for both of these methods are UB. Pretty much all you can do is memcpy.The portable way to do this is with
memcpy
(you may also be able to conditionally do it withreinterpret_cast
or a union, but those aren't certain to be portable because they violate the letter of the strict-alias rules):But before you do make sure you know exactly what you're doing and what floating point representation is being used (although IEEE754 is a popular/common choice). You'll want to avoid all kinds of problem values like infinity, NaN, and denormal numbers.