Assigning an exact representation to a floating point value

人走茶凉 提交于 2020-01-07 04:01:48

问题


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.



来源:https://stackoverflow.com/questions/46028570/assigning-an-exact-representation-to-a-floating-point-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!