简体   繁体   English

C:从字符数组复制到int

[英]C: Copying from a character array to an int

  // Works
  int fnamesize=0;
  fnamesize=message[0]<<24;
  fnamesize+=message[1]<<16;
  fnamesize+=message[2]<<8;
  fnamesize+=message[3];

  // Doesn't work
  int fsize;
  memcpy(&fsize,message,sizeof(int));

Can someone explain why the second one doesn't work? 有人可以解释为什么第二个无效吗? The memory I'm copying from, message is a char * . 我要复制的内存, message是一个char * When I try to test the values of fnamesize and fsize, like printf("fsize is %d,fnamesize is %d",fsize,fnamesize); 当我尝试测试fnamesize和fsize的值时,例如printf("fsize is %d,fnamesize is %d",fsize,fnamesize); , the fsize gives an unexpected value, but fnamesize gives the value I expect. ,fsize提供了意外的值,但fnamesize提供了我期望的值。

Thoughts? 有什么想法吗?

That's because of endianess , which means the layout of bytes in an int. 那是因为endianess ,这意味着int中字节的布局。

In windows, the second way will give you an int that has the opposite byte order, like this: 在Windows中,第二种方式将为您提供一个具有相反字节顺序的int,如下所示:

fsize=message[3]<<24;
fsize+=message[2]<<16;
fsize+=message[1]<<8;
fsize+=message[0];

尝试在有效的代码中更改数组索引的顺序,将结果与无效的代码进行比较,然后查找术语“大端”和“小端”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM