Here is the simple C++ program to check if a machine is little endian or big endian.
In the following program integer is stored in 4 bytes. We take a character pointer and point it to the integer address by type casting the address of x.
This context can be depicted in the memory as follows.
Let us assume the variable is stored at the memory address 1000. 1 is represented in Hex as 0x00000001 in 4 bytes format. On a big endian machine, the most significant byte (i.e 00) gets stored in the lowest memory address. On a little endian machine, the least significant byte (i.e 01) gets stored in the lowest address.
The character pointer also points to the memory location 1000, but it treats the data as a byte. So by looking at the value at Address 1000 (*cptr) we can say if the machine is big endian or little endian.
#include <iostream> |