gpt4 book ai didi

c++ - 在 C++ Visual Studio 中将字节直接从 float 复制到 unsigned int?

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:50 25 4
gpt4 key购买 nike

我试图在不使用任何隐式转换数学的情况下将 float 直接转换为无符号整数(因此不是 C 样式或静态转换),只是将字节直接复制到另一个。在 Windows Visual Studio 2015 中, float 和无符号整数的大小相同(4 字节),所以我认为这方面没有任何问题。 . .我想出了一个解决方案,但必须有更好的方法来做我想做的事。

unsigned int x = 3;
float y = 2.4565;
*reinterpret_cast<float*>(&x) = y;

这就是我想要的,并将 X 设置为 1075656524。

如果有的话,我更喜欢跨平台解决方案。我知道类型的大小因平台而异,所以这可能是不可能的。

编辑:澄清一下,我希望将 float 的所有字节原封不动地复制到 unsigned int 中。存储在 float 中的每一位都应该存储在无符号整数中。还有不使用memcpy的解决方案吗?我想避免使用已弃用的函数。

最佳答案

I am trying to convert a float directly into an unsigned integer WITHOUT ANY OF THE IMPLICIT CONVERSION MATH, (so not the C style or static casts) just copying the bytes directly to the other

您似乎只想将位模式从一个内存位置复制到另一个内存位置。标准库函数 memcpy 可用于此目的。只要意识到如果 sizeof(int)sizeof(float) 不同,所有这些都没有实际意义。

unsigned int x = 3;
float y = 2.4565;
static_assert(sizeof(int) == sizeof(float), "Can't memcpy a float to an int");
memcpy(&x, &y);

一种更便携的解决方案是使用 uint8_tint8_t 数组。

uint8_t x[sizeof(float)];
float y = 2.4565;
memcpy(x, &y);

现在您可以通过检查数组元素的值来检查位模式。

关于c++ - 在 C++ Visual Studio 中将字节直接从 float 复制到 unsigned int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45113192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com