Assigning an exact representation to a floating po

2019-08-26 02:32发布

问题:

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:

  1. watch in debugger the expression:

    +------------------------+----------------------|
    | Watch Expression       | Value                |
    +------------------------+----------------------|
    | *(long long int *)(&a) | 4594681439063077250  |
    +------------------------+----------------------|
    
  2. 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?

回答1:

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.



回答2:

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));


回答3:

My interpretation of the Strict Aliasing rule, says this would be UB

uint64_t x = 4594681439063077250;
double * a = (double *) & x;

your code is fine.