Search code examples
cmatharithmetic-expressions

Little endian or Big endian


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


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.