about summary refs log tree commit diff
path: root/buildtools/endiangen.c
blob: 07560c1023d2188e6452d043b668a777ec69c0b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*----------------------------------------------------------------------------
                                 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
bitsPerWord(void) {

    return MAX(sizeof(long), sizeof(int)) * 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");
    printf("#define BITS_PER_WORD %u\n", bitsPerWord());

    return 0;
}