Blob Blame History Raw
/*----------------------------------------------------------------------------
                                 endiangen
------------------------------------------------------------------------------
  This is a program to create C code that declares the endianness of the
  machine on which it is run.

  It generates something like this:

    #ifndef LITTLE_ENDIAN
    #define LITTLE_ENDIAN 1234
    #endif

    #ifndef BIG_ENDIAN
    #define BIG_ENDIAN 4321
    #endif
       
    #ifndef BYTE_ORDER
    #define BYTE_ORDER LITTLE_ENDIAN
    #endif

    #define BITS_PER_WORD 32
    #endif

    
  Really good code usually is not sensitive to endianness.  But fast,
  not-so-good code often is.  The best way for code to determine
  endianness is for it to do a runtime cast of an integer to an array
  of characters and see where the bytes land.  But if speed requires
  even sleazier code than that, use these macros.

-----------------------------------------------------------------------------*/
#include <stdio.h>
#include <unistd.h>

#define MAX(a,b) ((a) > (b) ? (a) : (b))

enum endianness {ENDIAN_LITTLE, ENDIAN_BIG};

static enum endianness
byteOrder(void) {
    
    enum endianness retval;

    union {
        unsigned char arrayval[2];
        unsigned short numval;
    } testunion;

    testunion.numval = 3;

    if (testunion.arrayval[0] == 3)
        retval = ENDIAN_LITTLE;
    else
        retval = ENDIAN_BIG;

    return retval;
}



static unsigned int
bitsPerLong(void) {

    return sizeof(long) * 8;
}



int
main(int argc, char **argv) {

    printf("/* This was generated by the program 'endiangen' */\n");
    printf("\n");
    printf("/* LITTLE_ENDIAN, BIG_ENDIAN, and BYTE_ORDER "
           "may come from the C library\n");
    printf("via ctype.h. */\n");
    printf("#include <ctype.h>\n");
    printf("#ifndef LITTLE_ENDIAN\n");
    printf("#define LITTLE_ENDIAN 1234\n");
    printf("#endif\n");
    printf("#ifndef BIG_ENDIAN\n");
    printf("#define BIG_ENDIAN 4321\n");
    printf("#endif\n");
    printf("\n");
    printf("#ifndef BYTE_ORDER\n");
    printf("#define BYTE_ORDER %s\n", 
           byteOrder() == ENDIAN_LITTLE ? "LITTLE_ENDIAN" : "BIG_ENDIAN");
    printf("#endif\n");
    printf("\n");

    return 0;
}