Program to check whether a system is big-endian or little-endian

Hi everyone, this post will teach you how to check whether a system is big-endian  or little-endian. I have written the program in one of most simplest way. The program is very easy, provided you know what is meant by Endianness. Endianness defines the order in which system stores the bytes of a multibyte value.

Endianness includes big-endian and little-endian systems. Big-endian system stores the Most significant byte (MSB) first and little-endian systems store the Least significant byte (LSB) first. Most of the personal laptop and systems which we use now are little-endian types, while most of the Power PC's use big-endian type of storing data. The term "big-endian" came from the famous novel "Gullivers Travels".

How to check the endianness of a system

Since you understood the concept, implementation won't be that difficult. It is as follows:-
  • Assign num=1
  • Create a char pointer which point to "num".
  • Check the de-refernced pointer.
  • If it is 1, the system is little-endian, else it is big-endian.
The program is as follows. I have done the program in mac-osx. The output is "little-endian".

#include<iostream>
#include<stdio.h>

using namespace std;
void checkEndianness();

int main()
{
    cout<<"Program to check whether system is big-endian or little-endian"<<endl;
    checkEndianness();
    return 0;
}

void checkEndianness()
{
    int num=1;
    char *ptr;
    ptr = (char *)&num;
    
    //checking the least significant bit of the number
    if(*ptr==1)
    {
        cout<<"System is little endian"<<endl;
    }
    else
    {
        cout<<"System is big-endian"<<endl;
    }
}

Program to check whether system is big-endian or little-endian
System is little endian

I hope this post helped everyone in understanding about endianness and how to check the endianness of a system. Please comment below if you have any doubts. All comments/queries will be responded in a days time. Suggestions are most welcome.

References

1) Endianness

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++