How is each byte in an integer stored in CPU / memory?

Pyjong picture Pyjong · Dec 3, 2009 · Viewed 7.7k times · Source

i have tried this

char c[4];
int i=89;
memcpy(&c[0],&i,4);
cout<<(int)c[0]<<endl;
cout<<(int)c[1]<<endl;
cout<<(int)c[2]<<endl;
cout<<(int)c[3]<<endl;

the output is like:
89
0
0
0

which pretty trains my stomache cuz i thought the number would be saved in memory like 0x00000059 so how come c[0] is 89 ? i thought it is supposed to be in c[3]...

Answer

Goz picture Goz · Dec 3, 2009

Because the processor you are running on is little-endian. The byte order, of a multi-byte fundamental type, is swapped. On a big-endian machine it would be as you expect.