Next Up Previous Contents
Next: A.2 fpp.c
Up: A Example programs
Previous: A Example programs
[ID index][Keyword index]

A.1 islittlendian.c

If you want to find out, possibly as part of a script, whether a particular platform is big- or little-endian, the information will probably be squirrelled away somewhere in the headers for the compiler you're using, unfortunately not in any standard way. However, a portable way of doing this (which incidentally illustrates the contrast between the two systems) is to use this little program. It isn't bullet-proof, but if it fails, this is probably the least of your cross-platform problems. You can use the program as follows:


% echo '#define BIGENDIAN' \
    `if ./islittleendian; then echo 0; else echo 1; fi` >bytesex.h
to create a file bytesex.h with either #define BIGENDIAN 1 or #define BIGENDIAN 0 in it.

main () {
    /* Are we little or big endian?  Originally from Harbison and Steele. */
    union
    {
	long l;
	char c[sizeof(long)];
    } u;
    u.l = 1;
    exit (u.c[sizeof(long)-1] == 1);
    /* Return 0 (success) if we're little-endian, or 1 (fail) if big-endian */
}


Next Up Previous Contents
Next: A.2 fpp.c
Up: A Example programs
Previous: A Example programs
[ID index][Keyword index]
Theory and Modelling Resources Cookbook
Starlink Cookbook 13
Norman Gray
2 December 2001. Release 2-5. Last updated 10 March 2003