Using unions to reinterpret values

suggest change

Since C99, writing one union member and reading another reinterprets the object representation in the new type. That is defined, not a compiler extension. The reinterpreted value can be a trap representation. C89 did not state this clearly. Reading through a pointer of an incompatible type is a different operation and is undefined behavior under the strict-aliasing rules.

The “Fast Inverse Square Root” algorithm depends on IEEE-754 binary32 layout, not only on union type punning. It was used in graphics code because it was faster and less accurate than a square-root operation. The unsigned right shift has to be logical, so the integer member is uint32_t. A signed shift of a negative value is implementation-defined and is not the published trick. float is not required to be 32-bit or IEEE-754, so the function is not portable.

#include <stdint.h>

union floatToInt
{
    uint32_t intMember;
    float floatMember; /* Must be IEEE-754 binary32 for this to work */
};

float inverseSquareRoot(float input)
{
    union floatToInt x;
    uint32_t i;
    float f;
    x.floatMember = input;     /* Store the float member */
    i = x.intMember;           /* Read the same bytes as uint32_t */
    i = 0x5f3759df - (i >> 1);
    x.intMember = i;           /* Store the integer member */
    f = x.floatMember;         /* Read those bytes as float */
    f = f * (1.5f - input * 0.5f * f * f);
    return f * (1.5f - input * 0.5f * f * f);
}

A pointer cast such as *(uint32_t *)&input breaks strict aliasing and is undefined behavior. The union version above is the form C permits.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents