27.6 Using integer instructions to do floating point operations (all processors)
Integer instructions are generally faster than floating point instructions, so it is often advantageous to use integer instructions for doing simple floating point operations. The most obvious example is moving data. Example:
FLD QWORD PTR [ESI] / FSTP QWORD PTR [EDI]
Change to:
MOV EAX,[ESI] / MOV EBX,[ESI+4] / MOV [EDI],EAX / MOV [EDI+4],EBX
Testing if a floating point value is zero:
The floating point value of zero is usually represented as 32 or 64 bits of zero, but there is a pitfall here: The sign bit may be set! Minus zero is regarded as a valid floating point number, and the processor may actually generate a zero with the sign bit set if for example multiplying a negative number with zero. So if you want to test if a floating point number is zero, you should not test the sign bit. Example:
FLD DWORD PTR [EBX] / FTST / FNSTSW AX / AND AH,40H / JNZ IsZero
Use integer instructions instead, and shift out the sign bit:
MOV EAX,[EBX] / ADD EAX,EAX / JZ IsZero
If the floating point number is double precision (QWORD) then you only have to test bit 32-62. If they are zero, then the lower half will also be zero if it is a normal floating point number.
Testing if negative:
A floating point number is negative if the sign bit is set and at least one other bit is set. Example:
MOV EAX,[NumberToTest] / CMP EAX,80000000H / JA IsNegative
Manipulating the sign bit:
You can change the sign of a floating point number simply by flipping the sign bit. Example:
XOR BYTE PTR [a] + (TYPE a) - 1, 80H
Likewise you may get the absolute value of a floating point number by simply ANDing out the sign bit.
Comparing numbers:
Floating point numbers are stored in a unique format which allows you to use integer instructions for comparing floating point numbers, except for the sign bit. If you are certain that two floating point numbers both are normal and positive then you may simply compare them as integers. Example:
FLD [a] / FCOMP [b] / FNSTSW AX / AND AH,1 / JNZ ASmallerThanB
Change to:
MOV EAX,[a] / MOV EBX,[b] / CMP EAX,EBX / JB ASmallerThanB
This method only works if the two numbers have the same precision and you are certain that none of the numbers have the sign bit set.
If negative numbers are possible, then you have to convert the negative numbers to 2-complement, and do a signed compare:
MOV EAX, [a] MOV EBX, [b] MOV ECX, EAX MOV EDX, EBX SAR ECX, 31 ; copy sign bit AND EAX, 7FFFFFFFH ; remove sign bit SAR EDX, 31 AND EBX, 7FFFFFFFH XOR EAX, ECX ; make 2-complement if sign bit was set XOR EBX, EDX SUB EAX, ECX SUB EBX, EDX CMP EAX, EBX JL ASmallerThanB ; signed comparisonThis method works for all normal floating point numbers, including -0.