Programmatically determine endianess of the host machine

August 4, 2006 at 5:16 PMAmer Gerzic

Couple of days ago I was asked by a fellow software developer the question regarding endianess of host machine. The question was if there is an easy way to determine if a host machine is little or big endian. At first, I was somewhat shocked that such a simple question was not already answered throughout his carrier. But then I realized that he is a VB developer (no offense intended) and that he never had to deal with questions like this. Also, I realized with growing popularity of .NET and Java, the separation between software implementation and hardware is growing exponentially. It is reality that some software developers will probably spend whole life developing successful applications without even knowing that endianess exists. Is this a good or bad thing, I leave the reader to decide.

Getting back to the question, I wrote little example that would determine if machine is little or big endian. Here is the code:

#include <iostream>
using namespace std; 

int main(int argc, char* argv[])
{
    unsigned int x = 0x00000001;
    unsigned char *p = (unsigned char*)&x;
    if(p[0]=1)
        cout << "The machine is little-endian" << endl;
    else cout << "The machine is big-endian" << endl; 

    return 0;
}

Posted in: CPP | Win32 API

Tags:

Add comment

biuquote
Loading