HomeAbout UsContact Us

Simple code to find endianness in C

By embeddedSoft
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.


Tags

#c#endianness#embedded

Share


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

embeddedSoft

Insightful articles on embedded systems

Related Posts

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

Quick Links

Advertise with usAbout UsContact Us

Social Media