Inefficiency of `mod'

Adriaan van Os gpc at microbizz.nl
Mon Oct 25 14:30:34 CEST 2010


Maurice Lombardi wrote:
> Le 25/10/2010 12:13, Prof A Olowofoyeku (The African Chief) a écrit :
>> On 25 Oct 2010 at 11:21, Jonas Maebe wrote:
>>
>>> Actually, it's rather strange: "shr" is a logical shift right (both in
>>> FPC and Borland Pascal, and I assume also in GPC) as opposed to an
>>> arithmetic shift right. So I guess that Kylix and GPC also perform a  64
>>> bit logical shift right on the value, but then unlike FPC truncate  the
>>> result back to 32 bits. Otherwise I'm not sure where the "-1"  comes
>>> from when doing "(-2)shr 1".
>>
>> I don't much understand what all this is about, but for what it's
>> worth, here are my results with Delphi (3, 4, and 7) and BP 7.0.
>>
>> program unary;
>> begin
>>     writeln( -1 ); { -1 }
>>     writeln( 2 shr 1 ); { 1 }
>>     writeln((-2)shr 1 ); { -1; BP7=2147483647 }
>>     writeln(-(2 shr 1)); { -1 }
>>     writeln( -2 shr 1 ); { -1; BP7=2147483647 }
>>     writeln( -2 div 2 ); { -1 }
>> end.
> 
> This means that GPC does an arithmetical right shift (i.e. propagating 
> the 1 (or 0) in the leftmost (highest weight) position), while BP does a 
> logical right shift.
> It seems more sound to use an arithmetical shift for integer and a 
> logical shift for cardinal. Standard does not help since it does not 
> define the shift operators. C (and BP?) are too mind confused to enforce 
> this point.

Ah, that adds an interesting case, mentioned here <http://en.wikipedia.org/wiki/Arithmetic_shift>, 
namely the arithmetic shift right of -1.

program arithmeticshift;
begin
   writeln( -(1 shr 1));
   writeln( -1 shr 1);
   writeln( (-1) shr 1)
end.

GPC prints
0
0
-1

FPC prints
0
9223372036854775807
9223372036854775807

Regards,

Adriaan van Os






More information about the Gpc mailing list