In this question the OP tried to isolate an elusive bug in a big program. He observed some double
values and then tried to hard code them as input to a smaller test program. The ideea is great for isolating such a bug.
The method chosen however violates the String Aliasing rule, introducing UB, thus the test is completely unreliable:
watch in debugger the expression:
+------------------------+----------------------| | Watch Expression | Value | +------------------------+----------------------| | *(long long int *)(&a) | 4594681439063077250 | +------------------------+----------------------|
and then assign it in the test program:
double a; *(long long int *)(&a) = 4594681439063077250;
(I strongly suspect) He did this in order to preserve the exact double
value, bit by bit.
The question: How to assign to a double the exact value - bit by bit - observed in a debug session?
Hexadecimal representation is a good way to assign the exact bit representation of a floating point value. If you cannot use literals because you are not yet on C++ 17, note that strtod recognizes this format.
This can be accomplished by representing the double as an array of char
:
double as_double = 0.0;
uint64_t as_uint64 = 4594681439063077250 ;
static_assert(sizeof(double) == sizeof(uint64_t), "");
memcpy(&as_double, &as_uint64_t, sizeof(double));
My interpretation of the Strict Aliasing rule, says this would be UB
uint64_t x = 4594681439063077250;
double * a = (double *) & x;
your code is fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.