Simple code to find endianness in C

Graphic showing chip

Endianness is the order of storage of bytes of a word in memory; there are big-endian and little-endian systems. Often in latest microcontrollers there is option to switch between big-endian and little-endian schemes.

Big-endian: Stores the Most Significant Byte (MSB) of the data word in the smallest address in memory.

Little-endian: Stores the Least Significant Byte (LSB) of the data word in the smallest address in memory.

This C program shows a very simple program to detect the endianness of the system.

Code walk-through

This example C program implements a simple logic to detect endianness of the machine.

The condition check at line,

tests if the variable i typecasted to a character pointer results in the value 1 if dereferenced. The integer i is set to value 1 in the main(). Since the little endian machine saves its LSB at lower address; if the integer variable address is typecasted to a character pointer and a dereferncing operation will result in fetching the value stored at the lowest memory location.

So here in this example, if we get a value 1 after dereferencing the typecasted variable i we can be sure that the machine is a little endian machine or otherwise.


Leave a Reply 0

Your email address will not be published. Required fields are marked *