Programmatically determine endianess of the host machine

by Amer Gerzic 4. August 2006 17:16

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;
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C++ | Win32 API

Comments

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

Who is Amer?

Amer Gerzic is Vice President of Operations at Presort Services Inc. and founder of Infinity Software Solutions LLC. For futher information please check LinkedIn profile.

View Amer Gerzic's profile on LinkedIn

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008