Micro-GMP

Vincent Lefevre vincent at vinc17.net
Fri Nov 30 16:56:58 UTC 2018


On 2018-11-30 17:20:24 +0100, Marco Bodrato wrote:
> Il Ven, 30 Novembre 2018 4:24 pm, Vincent Lefevre ha scritto:
> > With the correct signs:
> >
> > #define GMP_NEG_CAST(T,x) (((T) -((x) + 1)) + 1)
> 
> Of course, you are right. (I messed up the e-mail a little bit, and sent
> the intended message as an attachment...)
> 
> > but I still don't see any advantage.
> 
> Well, -((x) + 1) is computed as a signed type, and avoids the possible
> issue of representing -LONG_MIN with signed.

The representation itself doesn't matter for the specification of the
operations (there are no bitwise operations involved here). What can
matter in the code is the set of the representable values: LONG_MIN
can *mathematically* be either - LONG_MAX - 1 (with two's complement)
or - LONG_MAX (with the other two representations). The asymmetry is
there only with two's complement, so that in general, if you have a
portable solution for two's complement, it will be OK with the other
representations.

> Moreover -((x) + 1) is non negative, so that there are no problems
> in casting it to an unsigned type.

Yes. However, the C standard completely specifies conversions to
unsigned integer types, in term of modular arithmetic.

> Paul did not use a cast in his code, so he had to use the -(x + 1) form.
> 
> I understand this version better than the one we have in the code...
> 
> Anyway, if someone can suggest the most _portable_ way to define the
> macro, we can change its definition (both in mini- and in GMP).

The simplest macro is:

#define GMP_NEG_CAST(T,x) (- (T) (x))

When one understands modular arithmetic, this is actually easier
to read. This can be understood as: We compute the mathematical
expression -x in modular arithmetic, and since -x (as an integer)
is representable in T, one gets the integer -x. One doesn't have
to think about representations and what intermediate values are
involved.

-- 
Vincent Lefèvre <vincent at vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)


More information about the gmp-devel mailing list