[fpc-pascal] Conversion from C to Pascal - Left bit shift

Jonas Maebe jonas at freepascal.org
Sat Sep 4 12:22:51 CEST 2021


On 03/09/2021 08:02, LacaK via fpc-pascal wrote:

>> I have code in C like this:
>>   E1 << E2
>> If E1 is of unsigned type then "The value of E1 << E2 is E1
>> left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has
>> an unsigned type, the value of the result is E1 × 2^E2, reduced modulo
>> one more than the maximum value representable in the result type."
>>
>> I understand this as result of such operation does not grow over 32
>> bits, right?
>>
>> In Pascal I have:
>>   E1 shl E2
>> where E1 is of LongWord type.
>>
>> On 64-bit target this result of shl can overcome 32 bits (iow operates
>> on 32 bits)?

If E1 is 32 bits, the result will be 32 bits. From the compiler source code:

{ calculations for ordinals < 32 bit have to be done in
  32 bit for backwards compatibility. That way 'shl 33' is
  the same as 'shl 1'. It's ugly but compatible with delphi/tp/gcc }

Note that the "shl 33' is the same as 'shl 1'" part of the comment
refers to the specific behaviour of the x86 family of processors. That
is not necessarily the case on other systems (e.g. on 32 bit PowerPC,
the result will be 0 as you would normally expect).

> Can we say that in Pascal the result of:
>   E1 shl E2
> is of same type as E1 ?

No. If E1 is smaller than 32 bits, the result will be promoted to
1) on 32/64 bit platforms: 32 bits
2) on 8/16 bit platforms: the smallest integer type that can represent
both E1 and the native integer type of the platform

> What if there is an expression on left side:
>   (E1*x) shl E2
> Will E1*x promote to 64 bits (on 64 bit target)?

Expressions are always evaluated independently of how their result is
used. So, yes.


Jonas


More information about the fpc-pascal mailing list