Byte Swapping Floating-Point Values

Even on a single platform there can be many different representations for floating-point values. Unless you are very careful, attempting to pass floating-point values across platform boundaries causes no end of headaches. To help you work with floating-point numbers, Utility Services defines a set of functions and two special data types in addition to the integer-swapping functions. These functions allow you to encode 32-and 64-bit floating-point values in such a way that they can later be decoded and byte swapped if necessary. Listing 1-5 shows you how to encode a 64-bit floating-point number and Listing 1-6 shows how to decode it.

Listing 1-5 Encoding a Floating Point Value

Float64             myFloat64;
CFSwappedFloat64    swappedFloat;

// Encode the floating-point value.
swappedFloat = CFConvertFloat64HostToSwapped(myFloat64);
Listing 1-6 Decoding a floating-point value

Float64             myFloat64;
CFSwappedFloat64    swappedFloat;

// Decode the floating-point value.
myFloat64 = CFConvertFloat64SwappedToHost(swappedFloat);

The data types CFSwappedFloat32 and CFSwappedFloat64 contain floating point values in a canonical representation. A CFSwappedFloat is not itself a float, and should not be directly used as one. You can however send one to another process, save it to disk, or send it over a network. Because the format is converted to and from the canonical format by the conversion functions, there is no need for explicit swapping API. Byte swapping is taken care of for you during the format conversion if necessary.


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