[fpc-pascal] shift right operation with variables

Marco van de Voort marcov at stack.nl
Mon Aug 17 15:59:08 CEST 2015

In our previous episode, Xiangrong Fang said:
> var
>   res: Integer;
>   mask1, mask2: QWord;
> begin
>   mask1 := $FFFFFFFFFFFFFFFF shr 24;
>   WriteLn(IntToHex(mask1, 16));
>   res := 24;
>   mask2 := $FFFFFFFFFFFFFFFF shr res;
>   WriteLn(IntToHex(mask2, 16));
> end.
> Why they are different? How can I ensure the result is like SHR with
> constant.

The first are two literals and is calculated at compiletime using the rules
for literals.

In the second is calculated at runtime one is typed an integer, probably the
large constant is downcast to integer.

To avoid that cast it to qword()

   mask2 := qword($FFFFFFFFFFFFFFFF) shr res;

More information about the fpc-pascal mailing list