How to check whether system is Big or Little Endian using C?

Problem : Write a optimized code to check whether the system is Big or Little Endian using C

Understanding:

Endianness of the system describes how the multibyte data are stored(int, float..etc).

Let us take example of Big Endian vs Little Endian representation of number 0x11223344

Using above idea, we can use below program to check the endianess of the system

//C program to check the endianess of the system
#include <stdio.h>
int main() {
    unsigned int number = 1;
    
    /*Take only the first byte*/
    char *i = (char*)&number;
    
    /*If the bit is 1, then it is Little otherwise Big Endian*/
    if(*i)
        printf("System is Little Endian");
    else
        printf("System is Big Endian");
    
    return 0;
}

Output:

System is Little Endian

Explanation : In the above example code, character pointer i is pointing to integer number . Character takes only 1 byte of data. So it will store only the first byte of the integer. Based on the System Endianess, it will have value either 1 or 0.

1 indicates that system is Little Endian.

0 indicates that system is Big Endian.

You can learn more about Endianess : https://en.wikipedia.org/wiki/Endianness

Leave a Comment