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?
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'
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With