Re: 64bit/64bit fixed point division?



Phil Carmody wrote:
Terje Mathisen <spamtrap@xxxxxxxxxx> writes:
; Make sure that the x87 part is set to extended precision first!

FILD qword ptr [a]
FILD qword ptr [b]
FDIVP st(1),st
FMUL [two_to_32] ; Do a 32-bit left shift to convert fraction
FISTP qword ptr [result]

.... and I'm still interested quite how you'd use an integer divisor.
This is about 50-60 cycles on anything from a classic Pentium and up.

And only works if the integer is 63 bits precision, /not/ 64.
That damn sign bit can be a pain in the arse sometimes...

Phil, the original poster did not state that he worked with unsigned numbers, so my code should work as is. The extended format for fp numbers work with 1+15+64 bits, with an explicit leading 1 bit, so even unsigned 64-bit numbers will be stored exactly.

However, if you do need 64-bit unsigned, then you can still use the fp divisor, albeit with one or two small tweaks:

a) Pretend that the numbers are signed, then adjust after the fact if needed.

b) Load the 64-bit value as two 32-bit unsigned numbers, then do the FDIV and convert back.

c) Load only the divisor, convert to a reciprocal, store that as an unsigned integer, then do a reciprocal multiplication to generate the true result.

c) Inspect the numbers before you start, and then handle the different cases in the following way: (result = a/b)

1) (a) and (b) both positive: Use my original code.
2) At least one of (a) and (b) negative, i.e. top bit set:
Load both numbers in two stages, then do the same division as in (1).

One possibility is that you can get into an overflow situation, where the result won't fit inside the 32:32 target field. How do youwant to handle this? Trap, overflow silently (truncating the most significant bits?), saturate to 0xffff... ?

Terje
--
- <Terje.Mathisen@xxxxxxxxxxxxx>
"almost all programming can be viewed as an exercise in caching"



***********************************************************************
NOTICE: This e-mail transmission, and any documents, files or previous
e-mail messages attached to it, may contain confidential or privileged
information. If you are not the intended recipient, or a person
responsible for delivering it to the intended recipient, you are
hereby notified that any disclosure, copying, distribution or use of
any of the information contained in or attached to this message is
STRICTLY PROHIBITED. If you have received this transmission in error,
please immediately notify the sender and delete the e-mail and attached
documents. Thank you.
***********************************************************************