just noticed something
bytes of integers (probably also other types of primitives which has more than 1 bytes) are stored reversed, i mean
int a = 0x01020304;
is actually stored as 04 03 02 01 as in memory.
I might be mistaken but I think that is the case, I first noticed this while I looking a dat file in hex editor. After that wrote a program like that
int a = 0x01020304;
char *c = (char*)&a
printf("%d %d %d %d", *c, *(c+1), *(c+2), *(c+3));
and result is 4 3 2 1.
am I making some huge mistake or it is really reversed? if it is, what is the reason?
You're not mistaken. Intel CPUs are what's called Little Endian, which means the least significant byte is stored first.
The usual reason given for choosing little endian is that casting between smaller integer types and larger integer types doesn't require that you change the address you're looking at. That is, given the following code:
*sp will contain the value you "expect" (that is, 1234). On a big-endian system, *sp would contain 0.
Not that you'd ever actually do what I posted above, of course :-) In most cases, when designing a CPU, it's a pretty arbitrary decision whether you choose to be big endian or little endian.
Edit: too slow!
The usual reason given for choosing little endian is that casting between smaller integer types and larger integer types doesn't require that you change the address you're looking at. That is, given the following code:
int n = 1234;int *ip = &n;short *sp = reinterpret_cast<short *>(ip);
*sp will contain the value you "expect" (that is, 1234). On a big-endian system, *sp would contain 0.
Not that you'd ever actually do what I posted above, of course :-) In most cases, when designing a CPU, it's a pretty arbitrary decision whether you choose to be big endian or little endian.
Edit: too slow!
You've discovered what is known as "endianness". Bytes on x86 processors are stored in a low-byte first order. You can read more about it on wikipedia.
The C++ language hides endianness from the programmer, and allows the programmer to specify numbers in a high-byte first order.
The C++ language hides endianness from the programmer, and allows the programmer to specify numbers in a high-byte first order.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement