memcpy 没有按预期执行
我有这段输出错误结果的代码。
#include <stdio.h>
#include <string.h>
int main()
{
unsigned char bytes[4];
float flt=0;
bytes[0]=0xde;
bytes[1]=0xad;
bytes[2]=0xbe;
bytes[3]=0xef;
memcpy( &flt, bytes, 4);
printf("bytes 0x%x float %e\n", flt, flt);
return 0;
}
我得到的输出是
字节0xc0000000浮点数-2.000001e+00
我期望得到
字节0xdeadbeef浮点-6.2598534e+18
编辑#1 正如所指出的,字节序可能不同,这将导致以下结果
字节0xefbeadde浮点-1.1802469e+29
我不明白的是从 float 到 unsigned int 的转换导致 0xc0000000 (同一 printf 语句中的 float 为 -2.0000 我将归因于编译器优化)
这之前在不同的版本上工作过电脑。 这可能是架构的改变。
I have this bit of code that is outputting the wrong results.
#include <stdio.h>
#include <string.h>
int main()
{
unsigned char bytes[4];
float flt=0;
bytes[0]=0xde;
bytes[1]=0xad;
bytes[2]=0xbe;
bytes[3]=0xef;
memcpy( &flt, bytes, 4);
printf("bytes 0x%x float %e\n", flt, flt);
return 0;
}
the output that I get is
bytes 0xc0000000 float -2.000001e+00
I am expecting to get
bytes 0xdeadbeef float -6.2598534e+18
edit #1
as was pointed out the endianness could be different which would result in the following
bytes 0xefbeadde float -1.1802469e+29
what I don't understand is the cast from float to unsigned int resulting in 0xc0000000 (the float in the same printf statement being -2.0000 I would attribute to compiler optimization)
this was working before on a different computer. It could be an architecture change.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
不是memcpy的问题。
...
时,float
总是转换为double
,因此在大多数英特尔架构上你无法获得 4 个字节。0xdeadbeef
时,您假设您的架构是 BIG endian。 有许多小端架构,例如 Intel x86。It is not problem of memcpy.
float
is allways converted todouble
when passed over...
of printf, so you just can't get 4 bytes on most of intel architectures.0xdeadbeef
in this code, you assume that your architecture is BIG endian. There are many little endian architectures, for example Intel x86.