A little warning in GMP.h

Brian Hurt bhurt at spnz.org
Wed Sep 22 20:53:48 CEST 2004

On Wed, 22 Sep 2004, Francesco Montorsi wrote:

>     return __gmp_l & (-(mp_limb_t) (__gmp_n != 0));

On a two's complement binary machine, this returns __gmp_l is __gmp_n != 
0, otherwise it returns 0.

How it works:

__gmp_n != 0 evaluates to 1 if __gmp_n != 0, or to 0 otherwise.  Casting 
the value to type mp_limb_t increases the precision to be a full limb.  
Negating it converts the number to -1, or 0xFFF...FFF (assuming a 
twos-complement machine), if __gmp_n != 0, or to 0 or 0x000...000 if 
__gmp_n == 0.  We then and this value with __gmp_l- if __gmp_n != 0, then 
we're evaluation __gmp_l & 0xFFF...FFF, which comes out to __gmp_p.  If 
__gmp_n == 0, then we're evaluation __gmp_l & 0x000...000, which comes out 
to 0.

The reason for this trickiness is that it's turned an unpredictable branch 
into a data dependency.

"Usenet is like a herd of performing elephants with diarrhea -- massive,
difficult to redirect, awe-inspiring, entertaining, and a source of
mind-boggling amounts of excrement when you least expect it."
                                - Gene Spafford 

More information about the gmp-discuss mailing list