Search code examples
c++ccastingx87

How does the CPU "cast" a floating point x87 (i think) value?


I just wanted to know how the CPU "Cast" a floating point number. I mean, i suppouse that when when we use a "float" or "double" in C/C++ the compiler is using the x87 unit, or am i wrong? (i couldn't find the answer) So, if this is the case and the floating point numbers are not emulated how does the compiler cast it?


Solution

  • I mean, i suppouse that when when we use a "float" or "double" in C/C++ the compiler is using the x87 unit, or am i wrong?

    On modern Intel processors, the compiler is likely to use the SSE/AVX registers. The FPU is often not in regular use.

    I just wanted to know how the CPU "Cast" a floating point number.

    Converting an integer to a floating-point number is a computation that is basically (glossing over some details):

    • Start with the binary (for unsigned types) or two’s complement (for signed types) representation of the integer.
    • If the number is zero, return all bits zero.
    • If it is negative, remember that and negate the number to make it positive.
    • Locate the highest bit set in the integer.
    • Locate the lowest bit that will fit in the significand of the destination format. (For example, for the IEEE-754 binary32 format commonly used for float, 24 bits fit in the significand, so the 25th bit after the highest bit set does not fit.)
    • Round the number at that position where the significand will end.
    • Calculate the exponent, which is a function of where the highest bit set is. Add a “bias” used in encoding the exponent (127 for binary32, 1023 for binary64).
    • Assemble a sign bit, bits for the exponent, and bits for the significand (omitting the high bit, because it is always one). Return those bits.

    That computation prepares the bits that represent a floating-point number. (It omits details involving special cases like NaNs, infinities, and subnormal numbers because these do not occur when converting typical integer formats to typical floating-point formats.)

    That computation may be performed “in software” (that is, with general instructions for shifting bits, testing values, and so on) or “in hardware” (that is, with special instructions for doing the conversion). All desktop computers have instructions for this. Small processors for special-purpose embedded use might not have such instructions.