开发者

C memcpy issues with unsigned char array

开发者 https://www.devze.com 2023-01-25 17:09 出处:网络
I have a question about memcpy that I hope someone can answer. Here\'s a short demonstrative program:

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 (开发者_如何学Pythonint 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号