Double from long bits

前端 未结 3 1631
名媛妹妹
名媛妹妹 2021-01-02 23:17

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

相关标签:
3条回答
  • 2021-01-02 23:37

    The portable way to do this is with memcpy (you may also be able to conditionally do it with reinterpret_cast or a union, but those aren't certain to be portable because they violate the letter of the strict-alias rules):

    // First, static assert that the sizes are the same
    memcpy(&result, &bits, sizeof(bits));
    

    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.

    0 讨论(0)
  • 2021-01-02 23:37

    Beware of union and reinterpret_cast<double*>(&bits), for both of these methods are UB. Pretty much all you can do is memcpy.

    0 讨论(0)
  • 2021-01-02 23:59

    The following uses a void pointer.

    unsigned long long bits = 1ULL;
    void* tempPtr=(void*)&bits;
    double result = *(double*)tempPtr;
    
    0 讨论(0)
提交回复
热议问题