C:从字符数组复制到 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));
有人可以解释为什么第二个不起作用吗?我正在复制的内存 message
是一个 char *
。当我尝试测试 fnamesize 和 fsize 的值时,例如 printf("fsize is %d,fnamesize is %d",fsize,fnamesize);
,fsize 给出了意外的值,但 fnamesize 给出了我期望的值。
想法?
// 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 *
. When I try to test the values of fnamesize and fsize, like printf("fsize is %d,fnamesize is %d",fsize,fnamesize);
, the fsize gives an unexpected value, but fnamesize gives the value I expect.
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为 endianess,这意味着 int 中的字节布局。
在 Windows 中,第二种方法会给你一个具有相反字节顺序的 int,如下所示:
That's because of endianess, which means the layout of bytes in an int.
In windows, the second way will give you an int that has the opposite byte order, like this:
尝试更改有效代码中数组索引的顺序,将结果与无效代码进行比较,并查找术语“大端序”和“小端序”。
Try changing the order of the array indices in your code that works, compare the result to the code that doesn't work, and look up the terms "big endian" and "little endian".