Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program to check little vs. big endian [duplicate]

Tags:

c

byte

endianness

Possible Duplicate:
C Macro definition to determine big endian or little endian machine?

int main() {   int x = 1;    char *y = (char*)&x;    printf("%c\n",*y+48); } 

If it's little endian it will print 1. If it's big endian it will print 0. Is that correct? Or will setting a char* to int x always point to the least significant bit, regardless of endianness?

like image 325
ordinary Avatar asked Oct 09 '12 01:10

ordinary


2 Answers

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory           ----->     +----+----+----+----+     |0x01|0x00|0x00|0x00|     +----+----+----+----+     A     |    &x 

so (char*)(&x) == 1, and *y+48 == '1'. (48 is the ascii code of '0')

If it is big endian, it will be:

    +----+----+----+----+     |0x00|0x00|0x00|0x01|     +----+----+----+----+     A     |    &x 

so this one will be '0'.

like image 101
Marcus Avatar answered Sep 23 '22 06:09

Marcus


The following will do.

unsigned int x = 1; printf ("%d", (int) (((char *)&x)[0])); 

And setting &x to char * will enable you to access the individual bytes of the integer, and the ordering of bytes will depend on the endianness of the system.

like image 33
phoxis Avatar answered Sep 26 '22 06:09

phoxis