Portable Byte-Swapping Functions

about | archive

[ 2005-August-01 15:45 ]

One glaring omisson in the C Standard Library are functions to properly handle swapping bytes. These functions are required when reading data that is written in one endianess on a machine that uses a different endianess. The most famous example are the network to host and host to network conversion funtions. These functions exist because the Internet Protocol defines all numbers to be in big-endian format. Hence, on big-endian systems, these functions do nothing, and on little-endian systems they actually perform the byte swapping. However, what if you need to convert to and from little-endian format? Or what if you need to swap 64-bit values? In either case, the C Standard Library has nothing to offer you. I wish that FreeBSD's byte order functions were more widely adopted, as they are exactly what I want.

On Mac OS X, the header file <libkern/OSByteOrder.h> contains definitions of macros OSSwapHostToLittleInt64, OSSwapLittleToHostInt32, OSSwapBigToHostInt16, etc. These macros do exactly what you want, and will be critical for porting Mac OS X applications to x86 processors. Apple has some documentation about Mac OS X byte swapping functions as part of their Universal Binary Programming Guidelines.

On Linux the situation is much uglier. GLib provides a nice set of byte order macros. If you don't want a dependency on GLib, you can use the kernel's byte order macros, which are defined in <asm/byteorder.h> and have the form __le16_to_cpu, __cpu_to_be64, etc.