代码之家  ›  专栏  ›  技术社区  ›  Tanj

memcpy没有按预期行事

  •  1
  • Tanj  · 技术社区  · 17 年前

    #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;
    }
    

    我期待着得到

    正如所指出的,结尾可能不同,这将导致以下结果

    5 回复  |  直到 17 年前
        1
  •  8
  •   Artyom    17 年前

    这不是记忆的问题。

    1. float 始终转换为 double 当经过时 ...
    2. 0xdeadbeef 在这段代码中,您假设您的架构是大端序。有许多小字节序架构,例如Intel x86。
        2
  •  6
  •   anon anon    17 年前

    printf("bytes 0x%x float %e\n", flt, flt);
    

    您试图将真正的两个8字节值视为两个4字节值

        3
  •  2
  •   btmorex    17 年前

    printf中的“%x”需要一个无符号整数。你给它一个浮点数,它会自动转换,这不是你想要的。你想做这样的事情:

    printf("bytes 0x%x float %e\n", *((unsigned int *)&flt), flt);
    

    哦,正如其他人指出的那样,如果你在x86上,你不会看到0xdeadbeef,更像0xefbeadde。

        4
  •  1
  •   Artelius    17 年前

    printf("bytes 0x%x float %e\n", *(int *)&flt, flt);
    
        5
  •  1
  •   Andomar    17 年前

    要查看参数升级,请将声明从float更改为double。在我的机器上,它打印:

    bytes 0xefbeadde float -1.860545e+230