Public Group

just noticed something

This topic is 3202 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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?

Share on other sites
x86 is a "little-endian" platform

http://en.wikipedia.org/wiki/Endianness

Share on other sites
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:

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!

Share on other sites
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.

Share on other sites
wow, thank you guys. that was fast

• 10
• 10
• 9
• 48
• 12
• Forum Statistics

• Total Topics
631388
• Total Posts
2999716
×