aarbear
aarbear

Reputation: 31

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

Upvotes: 3

Views: 3246

Answers (3)

David Harris
David Harris

Reputation: 2340

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.

Upvotes: 8

Martin Beckett
Martin Beckett

Reputation: 96119

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

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

Upvotes: 1

Phong
Phong

Reputation: 6768

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.

Upvotes: 2

Related Questions