[fpc-devel] Math.DivMod results should be signed
JeLlyFish.software at gmx.net
Tue Mar 21 09:34:52 CET 2006
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,
> UnsignedDivResult, UnsignedModResult: Word;
> DivResult: SmallInt absolute UnsignedDivResult;
> ModResult: SmallInt absolute UnsignedModResult;
> DivMod(-39, 20, UnsignedDivResult, UnsignedModResult);
> 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
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)
> 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
More information about the fpc-devel