在 C++ Visual Studio 中将字节直接从 float 复制到 unsigned int?
Copying bytes directly from float to an unsigned int in C++ Visual Studio?
我正在尝试将浮点数直接转换为无符号整数,而无需任何隐式转换数学(因此不是 C 样式或静态转换),只是将字节直接复制到另一个。在 Windows Visual Studio 2015 年,浮点数和无符号整数的大小相同(4 字节),所以我认为这方面没有任何问题。 . .我想出了一个解决方案,但必须有更好的方法来做我想做的事。
unsigned int x = 3;
float y = 2.4565;
*reinterpret_cast<float*>(&x) = y;
这就是我想要的,并将 X 设置为 1075656524。
如果有的话,我更喜欢跨平台的解决方案。我知道类型的大小可能因平台而异,所以这可能是不可能的。
编辑:澄清一下,我希望将 float 的所有字节原封不动地复制到 unsigned int 中。存储在浮点数中的每一位都应该存储在无符号整数中。还有不使用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_t
或 int8_t
.
的数组
uint8_t x[sizeof(float)];
float y = 2.4565;
memcpy(x, &y);
现在您可以通过检查数组元素的值来检查位模式。
我正在尝试将浮点数直接转换为无符号整数,而无需任何隐式转换数学(因此不是 C 样式或静态转换),只是将字节直接复制到另一个。在 Windows Visual Studio 2015 年,浮点数和无符号整数的大小相同(4 字节),所以我认为这方面没有任何问题。 . .我想出了一个解决方案,但必须有更好的方法来做我想做的事。
unsigned int x = 3;
float y = 2.4565;
*reinterpret_cast<float*>(&x) = y;
这就是我想要的,并将 X 设置为 1075656524。
如果有的话,我更喜欢跨平台的解决方案。我知道类型的大小可能因平台而异,所以这可能是不可能的。
编辑:澄清一下,我希望将 float 的所有字节原封不动地复制到 unsigned int 中。存储在浮点数中的每一位都应该存储在无符号整数中。还有不使用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_t
或 int8_t
.
uint8_t x[sizeof(float)];
float y = 2.4565;
memcpy(x, &y);
现在您可以通过检查数组元素的值来检查位模式。