c++ - Testing for Endianness: Why does the following code work? -
while understand endianness, unclear on how code works below. guess question less endianness , more how char * pointer , int work i.e. type conversion. also, have made difference if variable word
not short
int
? thanks!
#define big_endian 0 #define little_endian 1 int byteorder() { short int word = 0x0001; char * byte = (char *) &word; return (byte[0] ? little_endian : big_endian); }
a short int made of 2 bytes, in case 0x00
, 0x01
. on little endian system, small byte comes first, in memory appears 0x01
followed 0x00
. big endian systems are, naturally, reversed. pointers short integers on little endian system:
----------------------- ----------------------- | 0x01 | 0x00 | | | | ----------------------- ----------------------- &word &word+1
char pointers, on other hand, incremented sequentially. thus, taking address of first byte of integer , casting char *
pointer, may increment through each byte of integer in memory-order. here's corresponding diagram:
------------ ------------ ------------ ------------ | 0x01 | | 0x00 | | | | | ------------ ------------ ------------ ------------ &byte &byte+1 &byte+2 &byte+3
Comments
Post a Comment