Reputation: 1151
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
Upvotes: 3
Views: 2418
Reputation: 564441
The conversion is not bitwise.
The first conversion converts the value to an unsigned integer:
uint64_t y = static_cast<uint64_t>(x); // y == 5
The second takes that integer, and converts it to a double of the same value
double z = static_cast<double>(y) // Convert 5 to 5.0
The fact that the types use the same amount of memory is irrelevant, as the static_cast
changes the type. You would see the same behavior if you converted to then from an uint32_t
, as well. It does not merely perform a bitwise conversion.
If you want to perform a bitwise conversion, you could do this via pointer manipulation:
double x = 5.5;
uint64_t y = *((uint64_t*)&x); // Will effectively be a "garbage" value
double z = *((double*)(&y)); // Will be 5.5
Upvotes: 10