First, if x is zero, return zero.
Next find the index of the highest-order non-zero bit in x. Call it i.
If i is less than 24, left-shift x by 23 - i to get a normalized significand. Now clear bit 23 to hide the implicit bit, and set bits 23:30 to 127 + i, which is the biased exponent. Return the result.
Otherwise, right-shift x by i - 23 to get a normalized significand via truncation, and clear the implicit bit and set the exponent as above. If your desired rounding mode is truncation or round-to-minus-infinity, you are done. Otherwise, you will need to look at the bits that were shifted off the bottom of x. If the desired rounding mode is round-to-plus-infinity and any of those bits are set, add one to the result and return. Finally, if the desired rounding mode is round-to-nearest-ties-to-even (IEEE-754 default), there are three cases:
- the trailing bits are
b0...: return the truncated result.
- the trailing bits are
b1000...: this is an exact halfway case. If we call the truncated result t, you need to return t + (t&1); i.e. round up only if t is odd.
- the trailing bits are
b1...1...: add one to the truncated result and return.