HomeAbout UsContact Us

Simple code to find endianness in C

By Jithin Tom
Published in Embedded C/C++
September 22, 2022
1 min read
Simple code to find endianness in C

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.

#include <stdio.h>
int main()
{
int i = 1;
if (*((char *)&i) == 1) puts("little endian");
else puts("big endian");
return 0;
}

Code walk-through

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

The condition check at line,

if (*((char *)&i) == 1) puts("little endian");

tests if the variable i type-casted 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 type-casted to a character pointer and a dereferencing 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 type-casted variable i we can be sure that the machine is a little endian machine or otherwise.

Frequently Asked Questions

How do you programmatically check CPU endianness in C?

Store a multi-byte integer like `1` (binary `0x0001`) in memory, cast its address to a `char*` pointer, and inspect the first byte. If the byte is `1`, it is Little-Endian; if it is `0`, it is Big-Endian.

What is the difference between Big-Endian and Little-Endian?

Big-Endian stores the most significant byte (MSB) at the lowest memory address. Little-Endian stores the least significant byte (LSB) at the lowest address.

Why does endianness matter in network protocols or file formats?

Network protocols (like IP/TCP) typically use Big-Endian (network byte order). If a Little-Endian microcontroller transmits multi-byte data, it must swap the byte order before transmission to prevent corruption.

Tags

#c#endianness#embedded

Share


Previous Article
Example C code to set 5 bits starting from position 10
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Implementation of Singly Linked List in C
Implementation of Singly Linked List in C
September 22, 2022
2 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media