On Tuesday 21 March 2006 04:37, Michalis Kamburelis wrote:

> I'm concerned with using DivMod in cases when Dividend is < 0. DivMod
> declaration is
>
>    procedure DivMod(Dividend: Integer; Divisor: Word;  var Result,
> Remainder: Word);
>
> which means that it doesn't allow for Result and Remainder to be < 0.

Which would seem correct, if this were really a modulo-operation.

Unfortunately, DivMod should really be called DivRem, because it does 
not calculate the modulus, but rather the remainder of the division 
operation. But at least the name of the result variable suggests so.

> But when Dividend is < 0, Result and/or Remainder sometimes have to
> be < 0. For example,
>
> var
>    UnsignedDivResult, UnsignedModResult: Word;
>    DivResult: SmallInt absolute UnsignedDivResult;
>    ModResult: SmallInt absolute UnsignedModResult;
> begin
>    DivMod(-39, 20, UnsignedDivResult, UnsignedModResult);
> end;
>
> gets me UnsignedDivResult = 65535 and UnsignedModResult = 65517. Of
> course when treating memory as signed values (DivResult and
> ModResult), I can "decipher" correct values (-1 and -19) but that's
> obviously unclean.

Agreed. This result proves, that on an x86 the IDIV instruction is used, 
which is a signed integer operation with _signed_ results. So if Delphi 
does it the same way, they really screwed up the interface, because 
then it only works correctly for non-negative Dividends and Divisors 
less than 32768.

> Sure I can also just use "div" and "mod"
> operators, they always get me correct values, but I understand that
> doing div and mod separately may be slower than DivMod on some
> processors.

Yes, just because you would do exactly the same operation twice.

> I know that DivMod arguments have to stay as Word for Delphi compat.

I suppose so, although it is wrong (or let's say: very restricted) 
anyway.

> But in the light of the above, it seems like a good idea to add
> overloaded DivMod version that returns Result and Remainder as signed
> values ?

It would be, definitely. Especially because it does seem to calculate it 
that way.


Vinzent.

_______________________________________________
fpc-devel maillist  -  fpc-devel@lists.freepascal.org
http://lists.freepascal.org/mailman/listinfo/fpc-devel

Reply via email to