Using SDL: Endian Independence

[Prev] Table Of Contents # Using the Simple DirectMedia Layer API ## Endian independence
Determine the endianness of the current system The C preprocessor define SDL_BYTEORDER is defined to be either SDL_LIL_ENDIAN or SDL_BIG_ENDIAN, depending on the byte order of the current system. A little endian system that writes data to disk has it laid out: [lo-bytes] [hi-bytes] A big endian system that writes data to disk has it laid out: [hi-bytes] [lo-bytes] | Tip: x86 systems are little-endian, PPC systems are big-endian.
Example:
    #include "SDL_endian.h"

    #if SDL_BYTEORDER == SDL_LIL_ENDIAN
    #define SWAP16(X)    (X)
    #define SWAP32(X)    (X)
    #else
    #define SWAP16(X)    SDL_Swap16(X)
    #define SWAP32(X)    SDL_Swap32(X)
    #endif
Swap data on systems of differing endianness SDL provides a set of fast macros in SDL_endian.h, SDL_Swap16() and SDL_Swap32(), which swap data endianness for you. There are also macros defined which swap data of particular endianness to the local system's endianness. | Tip: If you just need to know the system byte-order, but don't need all the swapping functions, include SDL_byteorder.h instead of SDL_endian.h
Example:
    #include "SDL_endian.h"

    void ReadScanline16(FILE *file, Uint16 *scanline, int length)
    {
        fread(scanline, length, sizeof(Uint16), file);
        if ( SDL_BYTEORDER == SDL_BIG_ENDIAN ) {
            int i;
            for ( i=length-1; i >= 0; --i )
                scanline[i] = SDL_SwapLE16(scanline[i]);
        }
    }
[Prev] Table Of Contents