Name

Shl Keyword

Syntax

Value shl Bits

Description

The shl operator performs a left shift of an integer Value by Bits bit positions. Vacated bits are filled in on the right with zero bits.

The Bits operand is interpreted as an unsigned integer, modulo the size of the Value. That is, if Value is a LongInt, Bits is interpreted modulo 32, and if Value has type Int64, Bits is interpreted modulo 64. In other words, only the least significant few bits of Bits are used to determine the shift amount.

Tips and Tricks

  • Remember that the size of the Integer and Cardinal types can change with new versions of Delphi. Use the fixed-size types if you need a specific number of bits, such as 32 for LongInt and LongWord.

  • Do not use the shl operator instead of multiplying by a power of two. If you mean multiplication, you should write multiplication. The shl operator does not check for overflow errors. Let Delphi’s compiler decide the best instruction to use.

Example

// Measure the size of an integer, which can vary between versions.
function BitsPerInteger: Integer;
var
  Test: Integer;
begin
  Test := 1;
  Result := 0;
  while Test <> 0 do
  begin
    Test := Test shl 1;
    Inc(Result);
  end;
end;

See Also

And Keyword, Not Keyword, Or Keyword, Shr Keyword, Xor Keyword

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.