Category Archives: Programming Puzzles

Write a program to check the endianness (Big endian or little endian) of the machine

We all know that while executing a program, they store their data in memory. Memory can assumed as a large array of bytes.
The endianness of the machine indicates in which order the data gets stored in the memory.

Please refer this and this link for a detailed introduction to this topic.

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.

Big endian format
Address Value
1000 00
1001 00
1002 00
1003 01
Little endian format
Address Value
1000 01
1001 00
1002 00
1003 00

#include <iostream>

using namespace std;

int main()
{
unsigned int x = 1;
char *cptr = (char*)&x;

if( *cptr)
cout<<"Little endian";
else
cout<<"Big endian";

return 0;
}