floating-pointieee-754base-conversionsingle-precision

How do I convert a big number (e.g. 1.23e29) to IEE 754 single-precision floating-point format?


I learned how to convert from decimal to IEEE 754 through here, but I have no idea of how to convert a really big number without having to divide it all by the method explained on the post.

For example, I have to convert -1.5845632e29 to IEEE 754 single-precision floating-point, is there an easiest way than to get log base 2 of this big number?


Solution

  • The examples below use Python. Note that this assumes you're more interested in a quick way to calculate it than a very accurate answer.

    You can't simply use log base 2 on the whole thing, this will only give you a sensible exponent. Then to find the mantissa you could split out the fractional part of the exponent result and raise two to that power again, then multiply by two to the power of the number of mantissa bits. The sign needs to be treated separately.

    The following yields an exponent (without the bias) and mantissa (1+23 bits, shown in hex):

    math.log(1.5845632e29, 2)
    96.99999995421683
    hex(int(math.floor(2**0.99999995421683*2**23)))
    '0xffffff'
    

    To combine it all, mask out the implied one of the mantissa, shift in the exponent+bias, and take the sign bit:

    hex((0xffffff & 0x7fffff) | ((96+127) << 23) | (1 << 31))
    

    The technique above has some limitations - it doesn't catch exceptions and there may be issues with accuracy. And beware that for small numbers you do need to use the negative fraction for calculating the mantissa. To do this more precisely or for different formats you may have to do the whole thing without floating point math functions.

    Here are the rough steps for a technique that works well if your tool or language can support arbitrarily large integers. This is easy in Python, for e.g. C you need special libraries.

    1. Write the number as a big integer of the actual value
    2. Find the power of two just below it
    3. Multiply by two to the power of the number of mantissa bits you need, apply any required rounding, then shift right by the exponent.
    4. Calculate the IEEE exponent by adding the bias