c++ - 转换之间的数据丢失

标签 c++ casting type-conversion

为什么我在以下转换之间丢失了数据,即使两种类型占用的空间量相同?如果转换是按位完成的,那么 x = z 应该是真的,除非数据在转换过程中被剥离,对吧?有没有办法在不丢失数据的情况下进行这两种转换(即 x = z)?

主要.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);
}

结果:

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

最佳答案

转换不是按位的。

第一个转换值转换为无符号整数:

uint64_t y = static_cast<uint64_t>(x);  // y == 5

第二个接受那个整数,转换它为相同值的 double 值

double   z = static_cast<double>(y) // Convert 5 to 5.0

类型使用相同数量的内存这一事实是无关紧要的,因为 static_cast 改变了类型。如果您从 uint32_t 转换为 then,您也会看到相同的行为。它不仅执行按位转换。

如果你想执行按位转换,你可以通过指针操作来实现:

double   x = 5.5;
uint64_t y = *((uint64_t*)&x);  // Will effectively be a "garbage" value
double   z = *((double*)(&y)); // Will be 5.5

关于c++ - 转换之间的数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17369248/

相关文章:

c++ - 如何在 "first-chance"期间使用 VS 调试器检查 C++ 异常对象?

c - 这个C Actor 有什么问题

java - 在 java 中初始化字节数组时,什么时候必须转换为字节?

php - 使用php将字符串转换为数组

c - 为什么,当我将 char[] 转换为 int 时,是否会得到按字节反转

typescript - 从联合类型中提取,其中鉴别器也是联合

c++ - 使用 SDL_FillRect 创建矩形

c++ - 在 SFML 中获取主机 IP 地址

c++ - ARM NEON C : Wrong answer

c# - 将对象列表转换到模型