Data loss between conversion

Posted by Alex Brooks on Stack Overflow See other posts from Stack Overflow or by Alex Brooks
Published on 2013-06-28T16:17:38Z Indexed on 2013/06/28 16:21 UTC
Read the original article Hit count: 256

Filed under:
|
|

Why is it that I loose data between the conversions below even though both types take up the same amount of space? If the conversion was done bitwise, it should be true that x = z unless data is being stripped during the conversion, right? Is there a way to do the two conversions without losing data (i.e. so that x = z)?

main.cpp:

#include <stdio.h>
#include <stdint.h>

int main() {
    double   x = 5.5;
    uint64_t y = static_cast<uint64_t>(x);
    double   z = static_cast<double>(y) // Desire : z = 5.5;

    printf("Size of double: %lu\nSize of uint64_t: %lu\n", sizeof(double), sizeof(uint64_t));
    printf("%f\n%lu\n%f\n", x, y, z);
}

Results:

Size of double: 8
Size of uint64_t: 8
5.500000
5
5.000000

© Stack Overflow or respective owner

Related posts about c++

Related posts about casting