Question

#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.

Était-ce utile?

La solution

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.

Autres conseils

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 ;)

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.

Endianness

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?

You are wrong about what is Big endian and what is little endian. Read this

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).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top