Reputation: 5300
#include <stdio.h>
union Endian
{
int i;
char c[sizeof(int)];
};
int main(int argc, char *argv[])
{
union Endian e;
e.i = 1;
printf("%d \n",&e.i);
printf("%d,%d,\n",e.c[0],&(e.c[0]));
printf("%d,%d",e.c[sizeof(int)-1],&(e.c[sizeof(int)-1]));
}
OUTPUT:
1567599464
1,1567599464,
0,1567599467
LSB is stored in the lower address and MSB is stored in the higher address. Isn't this supposed to be big endian? But my system config shows it as a little endian architecture.
Upvotes: 2
Views: 2414
Reputation: 3663
You system is definitely little-endian
. Had it been big-endian
, the following code:
printf("%d,%d,\n",e.c[0],&(e.c[0]));
would print 0
for the first %d
instead of 1
. In little-endian
1 is stored as
00000001 00000000 00000000 00000000
^ LSB
^Lower Address
but in big-endian
it is stored as
00000000 00000000 00000000 00000001
^LSB
^Higher Address
And don't use the %d
to print addresses of variables, use %p
.
Upvotes: 3
Reputation: 46778
00000001 (Hexadecimal: 32 bits)
^^ ^^
MS LS
Byte Byte
Least Significant Byte at lowest address => little-endian. The integer is placed into memory, starting from its little-end. Hence the name.
Upvotes: 2
Reputation: 13196
Looks good to me. "little endian" (aka "the right way" :-) means "lower-order bytes stored first", and that's exactly what your code shows. (BTW, you should use "%p" to print the addresses).
Upvotes: 0
Reputation: 1922
You are wrong about what is Big endian and what is little endian. Read this
Upvotes: 1
Reputation: 24956
You have the byte containing "1" (least significant) as first element (e.c[0]) and the byte containing "0" being the second one (e.c[1]). This is litte endian, isn't it?
Upvotes: 1
Reputation: 16243
For little endian, the least significant bits are stored in the first byte (with the lowest address).
That's what you're seeing, so it seems there is sanity ;)
Upvotes: 2