Manipulating floating-point values by the bit

To deal with floating-point numbers bit-by-bit with some prospect of portability, use the techniques below. They are derived from a public implementation of the functions such as Scalb, Logb, and NextAfter, functions (whose purpose is to obviate such bit manipulation).

TIP Use this information only as a last resort. The CommonPoint system supplies a set of portable functions to manipulate numbers.

The first technique is to cast a float value as an unsigned 32-bit integer. For example:

    #define FLOAT_BITS(x) *((uint32_t *) &(x))
The type uint32_t is defined in a proposed extension to Standard C to support machine-independent specification of integer types. The type names an unsigned 32-bit integer on any platform. The argument x should be a float value whose address may be taken. Use of FLOAT_BITS depends on the fact that the bits of a float, from most to least significant, are ordered as are the bits of an unsigned 32-bit integer.

NOTE The situation is more complicated for a double or long double value, where the value is handled in 32-bit pieces. In this case, you must account for the byte order of the platform.

Here are two ways to extract the unbiased exponent of a float value x.

      long  unbiasedExp1 = ((int) ((FLOAT_BITS(x) & 0x7F800000) >> 23)) - 127;
      float unbiasedExp2 = Logb(x);
Use of the global function Logb is simpler and more portable than masking and shifting the exponent bits. If x is subnormal, unbiasedExp2 is the (out of range) exponent as though x were normalized, while unbiasedExp1 is one less than the exponent of x as a subnormal value. The float value unbiasedExp2 has special values in case x is zero, infinite, or NaN. Note that applying integer operations to a floating-point value is not a particularly portable technique, as it requires the use of three magic numbers: the mask, the shift count, and the bias.


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker