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

1
  • what is the architecture of your machine ? Commented Nov 19, 2010 at 5:40

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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.
AMD64 is little endian too stackoverflow.com/questions/1024951/…
@aarbear or motorola architecture or itanium which has support for both little endian and big endian
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.

4 Comments

hahaha. no actually little endian has many advantages that big endian doesn't. just like 0-based indexing.
@Matt Joiner - STOP IT STOP IT NOW. Or you will be sent back to 1980 for time out.
@detly: Have we met before? Have you noticed a trend in my answers?
@Matt - I couldn't find a source for the quote, I thought it was some guy from Dec. Any idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.