The following guidelines, along with the strategies provided later in this chapter, will help ensure optimal byte-swapping code in your application.
Keep data structures in native byte-order while in memory. Only swap bytes when you read data from disk or write it to disk.
When possible, let the compiler do the work for you. For example, when you use function calls such as the Core Foundation function CFSwapInt16BigToHost, the compiler determines whether the function call does something for the processor you are targeting. If the code does nothing, the compiler won’t call the function. Letting the compiler do the work is more efficient than using #ifdef statements.
If you must access a large file, consider arranging the data in a way that limits the byte swapping that you must perform. For example, you can arrange the most frequently accessed data contiguously in the file. Then, you need to read and swap bytes only for that chunk of data instead of for the entire data file.
Use the __BIG_ENDIAN__ and __LITTLE_ENDIAN__ macros only if you must. Do not use macros that check for a specific processor type, such as __i386__ and __ppc__.
Choose a consistent byte-order approach and stick with it. That is, if you are reading and writing data from disk on a regular basis, choose the endian format you want to use. This eliminates the need for you to check the byte ordering of the data, and then to possibly have to swap the byte order.
Be aware of which functions return big-endian data, and use them appropriately. These include the BSD Sockets networking functions, the DNSServiceDiscovery functions (for example, TCP and UDP ports are specified in network byte order), and the ColorSync profile functions (for which all data is big-endian). The IconFamilyElement and IconFamilyResource data types (which also include the data types IconFamilyPtr and IconFamilyHandle) are always big-endian. There may be other functions and data types that are not listed here. Consult the appropriate API reference for information on data returned by a function. For more information see “Network-Related Data.”
Keep in mind that swapping bytes comes at a performance cost so swap them only when absolutely necessary.
Last updated: 2007-02-26