Fast Reciprocals of Power-of-Twos with IEEE-754 Floating-Points

It is quite common to have to compute a power-of-two: $2^p$, where $p\in\mathbb{Z}$. For IEEE-754 floating-points an expensive division (or power-instruction) can be avoided by exploiting the structure of the floating-point representation.

IEEE-754 32-bit floating-point binary presentation
By Codekaizen - Own work, CC BY 3.0

The IEEE-754 floating-point representation uses a biased exponent which can be used to represent power-of-twos precisely. In the case of the 32-bit single precision, the exponent is 8-bit long and has a -127 bias. Therefore to create $2^p$ the binary representation would be 0 for sign bit, 0 for the mantissa and $p + 127$ for the exponent. Unlike division, this would always create a precise representation of the (reciprocal of) power-of-two.

In code:

float power_of_two(int p) {
    const auto u = (127 + p) << 23;
    return *reinterpret_cast<const float*>(&u);