C++ memcpy 从双精度数组到浮点数组
是否可以安全地从双精度数组 memcpy 到浮点数组?
Is is possible to memcpy from a double array to a float array safely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
是否可以安全地从双精度数组 memcpy 到浮点数组?
Is is possible to memcpy from a double array to a float array safely?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
取决于你想要什么。这些值肯定不会被保留。如果您需要它,请使用
std::copy
。Depends on what you want. The values certainly won't be preserved. If you need that, use
std::copy
.问题在于,无法保证编译器的 double 二进制表示与 float 的等效表示。为了将memcpy用于多字节类型,底层表示必须相同(相同的布局)。您可以安全地将
float
复制到float
、将int
复制到int
以及将double
复制到 <代码>双。当源类型与目标类型不匹配时,您注定会遇到未定义的行为,例如从
long
复制到char
或float
到double
。memcpy
函数不会进行任何转换或执行任何提升。它只是复制。The problem is that there is no guarantee that the compiler's binary representation of a
double
is the equivalent representation of afloat
. In order to usememcpy
for multi-byte types is that the underlying representation must be the same (same layout). You can safely copyfloat
tofloat
,int
toint
anddouble
todouble
.You are destined for undefined behavior when the source type does not match the destination type, such as copying from
long
tochar
orfloat
todouble
. Thememcpy
function does not make any conversion or perform any promotions. It just copies.就像许多其他人的回答一样,使用 memcpy 不起作用,因为这两种类型(通常)大小不同。请访问 http://en.cppreference.com/w/cpp/language/ 查看更多信息类型,或更具体地说:
使用 std::copy 会给你一个编译器警告(至少对我来说在 VS2015/VS2017 编译器上),因为编译器不允许通过 std::copy 从 double 到 float 隐式精度损失,而不警告开发人员。如果您设置了
将警告视为错误
标志,您将收到编译器错误。相反,我建议使用 std::transform 函数,并结合执行特定转换的 lamda。这也更清楚地表明,实际上正在发生明显的精度损失。
Like many others have answered, using
memcpy
does not work since the two types are (generally) different in size. Please see more at http://en.cppreference.com/w/cpp/language/types, or more specifically:Using
std::copy
will give you a compiler warning (at least for me on the VS2015/VS2017 compiler) since the compiler does not allow the implicit loss of precision from double to float via std::copy, without warning the developer about it. And if you have thetreat warnings as errors
flag set, you will get a compiler error.Instead, I recommend using use the
std::transform
function, combined with a lamda performing the specific cast. This also clearer shows that an explicit loss-of-precision is actually taking place.一般情况下 - 不。
在特定情况下,在给定平台上,
float
和double
的表示可能相同,并且复制会成功。但无论如何,这没有任何实际意义。In general case - no.
In specific cases, on a given platform the representation of
float
anddouble
might be the same, and the copy will succeed. But it doesn't make any practical sense anyway.memcpy
与类型无关(只看到字节)并且无法进行类型转换。只需使用std::transform
正如 @AzP 所说:memcpy
is type agnostic (just sees bytes) and can't do type conversion. Just usestd::transform
as @AzP said: