Sign in to follow this  
shultays

just noticed something

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this