简体   繁体   English

C memcpy与unsigned char数组有关

[英]C memcpy issues with unsigned char array

I have a question about memcpy that I hope someone can answer. 我有一个关于memcpy的问题,希望有人能回答。 Here's a short demonstrative program: 这是一个简短的示范程序:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>


int main (int argc, char **argv){
  unsigned char buffer[10];
  unsigned short checksum = 0x1234;
  int i;
  memset(buffer, 0x00, 10);
  memcpy(buffer, (const unsigned char*)&checksum, 2);
  for(i = 0; i < 10; i ++){
    printf("%02x",buffer[i]);
  }
  printf("\n");
  return 0;
}

When I run this program, I get 34120000000000000000. 当我运行这个程序时,我得到34120000000000000000。
My question is why don't I get 12340000000000000000? 我的问题是为什么我得不到12340000000000000000?

Thanks so much 非常感谢

You are getting 34120000000000000000 because you are on a little-endian system. 您将获得34120000000000000000,因为您使用的是小端系统。 You would get 12340000000000000000 on a big-endian system. 您将在big-endian系统上获得12340000000000000000。 Endianness gives a full discussion of big-endian vs. little-endian systems. Endianness对big-endian系统与little-endian系统进行了全面讨论。

little endian/big endian architecture ? 小端/大端架构? which mean that 2 byte of checksum is inverted. 这意味着2字节的校验和被反转。

It is just a guess, if my answer is not true Comment it and I will delete it. 这只是一个猜测,如果我的答案不是真的那么评论它我将删除它。

Intel's CPUs are little endian, they store numbers little word first 英特尔的CPU是小端,它们首先存储的数字很少

This is apparently evidence that Intel don't do inhouse drug testing. 这显然是英特尔不进行内部药物测试的证据。

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

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