Byte Swapping Integers

Utility Services provides three optimized primitive functions for byte swapping-- CFSwapInt16 , CFSwapInt32 , and CFSwapInt64 . All of the other swapping functions use these primitives to accomplish their work. In general you will not need to use these primitives directly.

Although the primitive swapping functions swap unconditionally, the higher level swapping functions are defined in such a way that they do nothing when a byte swap is not required--in other words, when the source and host byte orders are the same. For the integer types, these functions take the forms CFSwapXXXBigToHost and CFSwapXXXLittleToHost , CFSwapXXXHostToBig , and CFSwapXXXHostToLittle where XXX is a data type such as Int32 . For example, if you were on a little-endian machine reading a 16-bit integer value from a network whose data is in network byte order (big-endian), you would use the function CFSwapInt16BigToHost . Listing 1-3 demonstrates this process.

Listing 1-3 Swapping a 16 bit Integer

SInt16  bigEndian16;
SInt16  swapped16;

// Swap a 16 bit value read from network.
swapped16 = CFSwapInt16BigToHost(bigEndian16);

The section CFByteOrder introduced the example of a simple C structure that was created and saved to disk on a little endian machine and then read from disk on a big-endian machine. In order to correct the situation, you must swap the bytes in each field. The code in Listing 1-4 demonstrates how you would use Core Foundation byte-swapping functions to accomplish this.

Listing 1-4 Byte swapping fields in a C structure

// Byte swap the values if necessary.
aStruct.int1 = CFSwapInt32LittleToHost(aStruct.int1)
aStruct.int2 = CFSwapInt32LittleToHost(aStruct.int2)

Assuming a big-endian architecture, the functions used in Listing 1-4 would swap the bytes in each field. Figure 1-3 shows the effect of byte swapping on the field aStruct.int1 . Note that the byte-swapping code would do nothing when run on a little-endian machine. The compiler should optimize out the code and leave the data untouched.

Figure 1-3 Four-byte little-endian to big-endian swap

© 2000 Apple Computer, Inc. (Last Updated 04 April 00)