简体   繁体   中英

C memcpy issues with unsigned char array

I have a question about memcpy that I hope someone can answer. 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.
My question is why don't I get 12340000000000000000?

Thanks so much

You are getting 34120000000000000000 because you are on a little-endian system. You would get 12340000000000000000 on a big-endian system. Endianness gives a full discussion of big-endian vs. little-endian systems.

little endian/big endian architecture ? which mean that 2 byte of checksum is inverted.

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

This is apparently evidence that Intel don't do inhouse drug testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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