C Program To Determine Byte Order (Endianness)

C programRecently I needed to needed to check the endianness of a machine. I assumed the machine was Little Indian but wanted to make sure, thus this C code snippet. It’s important to understand that endian.h is not cross-platform, and exist only on Linux machines. There are standard byte order functions you can use if you are on Windows to figure this stuff out. Perhaps I will show an example of that later.

ByteOrder.c


#include <stdio.h>
#include <endian.h>

int main (void)
{
#if BYTE_ORDER == LITTLE_ENDIAN
printf("system is little Endian \n");
#elif BYTE_ORDER == BIG_ENDIAN
printf("system is big Endian \n");
#else
printf("whats going on? \n");
#endif

return 0;
}
Advertisements

5 thoughts on “C Program To Determine Byte Order (Endianness)

  1. #include
    typedef union
    {
    int number;
    char ch[sizeof(int)];
    }MyUnion;

    int main
    {
    MyUnion obj;
    obj.number = 112;
    if(obj.ch[0] != 0)
    printf(“Little Endian”);
    else if(obj.ch[0] == 0)
    printf(“Big Endian”);
    }

  2. Unless I’ve misunderstood, Umair’s main function can be reduced to two lines. I’ve also switched the variables to fixed-width types:

    #include
    #include

    typedef union{
    int16_t n;
    int8_t c[2];
    }MyUnion;

    int main(void){
    MyUnion Un = {1};
    puts(!Un.c ? “Big Endian.” : “Little Endian.”);
    }

    I prefer the macro way, though.

  3. Also, there’s a problem with posting includes in the comments here. It doesn’t show up. The above should have included stdint.h and sttdio.h.

  4. Sorry if I’m spamming, but I made another simplification. You don’t need the union at all:

    #include “stdio.h”
    #include “stdint.h”

    int main(void){
    int16_t n = 1;
    puts(*((int8_t*)&n) ? “Little Endian.” : “Big Endian.”);
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s