3

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

aarbear
  • 31
  • 1
  • 2

3 Answers3

8

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.

David Harris
  • 2,332
  • 1
  • 13
  • 25
2

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.

Phong
  • 6,600
  • 4
  • 32
  • 61
  • Endianess is a good point, but I see the same results when I run this on two different machines, one an Intel P4 ant the other an AMD64 which I believe are little endian and big endian architectures, respectively. – aarbear Nov 19 '10 at 05:54
  • 1
    AMD64 is little endian too http://stackoverflow.com/questions/1024951/does-my-amd-based-machine-use-little-endian-or-big-endian – David Gelhar Nov 19 '10 at 06:02
  • @aarbear or motorola architecture or itanium which has support for both little endian and big endian – prap19 Nov 19 '10 at 17:04
1

Intel's CPUs are little endian, they store numbers little word first

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

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263