ZetCode

Bit manipulation in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

Pascal exposes the bit level of integers directly: and, or, xor, and not combine bits, and shl and shr move them left and right. These operators work on Boolean values as well, where they mean the logical connectives. This article covers the operators, the binary, hexadecimal, and octal literals, bit masks for flags, population count and parity, Gray code, packing an RGB colour into a 32-bit word, the difference between signed and unsigned shifts, and the TBits class for bit collections of any size.

The bitwise operators

and keeps a bit when both operands have it, or keeps it when either has it, and xor keeps it when the operands differ. not inverts every bit. A shl N shifts the bits left by N positions and fills the right side with zeros, which multiplies by 2N; A shr N shifts right, which divides by 2N and discards the remainder. The example uses 12 (%1100) and 10 (%1010).

bitops.pas
program bitops;
{$mode objfpc}{$H+}

var
  A, B: Integer;

begin
  A := 12;   { %1100 }
  B := 10;   { %1010 }

  WriteLn('A and B = ', A and B);
  WriteLn('A or  B = ', A or B);
  WriteLn('A xor B = ', A xor B);
  WriteLn('not A   = ', not A);
  WriteLn('A shl 1 = ', A shl 1);
  WriteLn('A shr 2 = ', A shr 2);
end.

12 and 10 is 8 (%1000), 12 or 10 is 14 (%1110), and 12 xor 10 is 6 (%0110). not 12 is -13 because Pascal integers use two's complement: the inverted 32-bit pattern of 12 is the representation of -13. Shifting 12 left by one gives 24, and shifting it right by two gives 3, the integer quotient of 12 divided by 4.

$ fpc -gl bitops.pas
$ ./bitops
A and B = 8
A or  B = 14
A xor B = 6
not A   = -13
A shl 1 = 24
A shr 2 = 3

Literals and binary strings

Pascal writes hexadecimal numbers with $, binary with %, and octal with &. The same values can be built at run time with BinStr(Value, Digits) and HexStr(Value, Digits), which return the digits padded to the requested width. These functions are handy for debugging and for protocols that print bit fields.

literals.pas
program literals;
{$mode objfpc}{$H+}

uses SysUtils;

begin
  WriteLn('%1010      = ', %1010);
  WriteLn('$FF        = ', $FF);
  WriteLn('&777       = ', &777);
  WriteLn('BinStr(10, 8) = ', BinStr(10, 8));
  WriteLn('HexStr(255, 4) = ', HexStr(255, 4));
  WriteLn('SizeOf(LongWord) = ', SizeOf(LongWord));
end.

%1010 is 10, $FF is 255, and &777 is 511. BinStr and HexStr do not include a prefix, so the program adds % or $ when it prints a literal. LongWord is an unsigned 32-bit type, which is the natural choice for a bit pattern that should not be sign-extended. The width argument is a minimum: a value that needs more digits is printed in full rather than being truncated.

$ fpc -gl literals.pas
$ ./literals
%1010      = 10
$FF        = 255
&777       = 511
BinStr(10, 8) = 00001010
HexStr(255, 4) = 00FF
SizeOf(LongWord) = 4

Masks

A mask is an integer with ones in the positions that matter and zeros elsewhere. To test a bit, combine the value with the mask using and and compare the result with zero. To set a bit, or the value with the mask; to clear it, and with the complement of the mask; to toggle it, xor with the mask. The example wraps these operations in functions and stores four flags in one byte.

masks.pas
program masks;
{$mode objfpc}{$H+}

type
  TFlag = (Readable, Writable, Executable, Hidden);

function HasFlag(Value: Byte; Bit: Integer): Boolean;
begin
  Result := (Value and (1 shl Bit)) <> 0;
end;

function SetFlag(Value: Byte; Bit: Integer): Byte;
begin
  Result := Value or (1 shl Bit);
end;

function ClearFlag(Value: Byte; Bit: Integer): Byte;
begin
  Result := Value and not (1 shl Bit);
end;

function ToggleFlag(Value: Byte; Bit: Integer): Byte;
begin
  Result := Value xor (1 shl Bit);
end;

var
  V: Byte;

begin
  V := 0;
  V := SetFlag(V, Ord(Readable));
  V := SetFlag(V, Ord(Writable));
  WriteLn('after set:    ', V, ' readable=', HasFlag(V, 0),
    ' writable=', HasFlag(V, 1));

  V := ClearFlag(V, Ord(Readable));
  WriteLn('after clear:  ', V, ' readable=', HasFlag(V, 0),
    ' writable=', HasFlag(V, 1));

  V := ToggleFlag(V, Ord(Hidden));
  WriteLn('after toggle: ', V, ' hidden=', HasFlag(V, 3));
end.

Setting the readable and writable bits produces 3, or %00000011. Clearing the readable bit leaves 2, and toggling the hidden bit adds 8, for 10. The functions take the bit number rather than the mask so that the caller does not have to write 1 shl N each time. A Pascal set of an enumeration, as described in the enumerations and sets article, does the same job with more type safety but with a limit of 256 members.

$ fpc -gl masks.pas
$ ./masks
after set:    3 readable=TRUE writable=TRUE
after clear:  2 readable=FALSE writable=TRUE
after toggle: 10 hidden=TRUE

Counting set bits

The population count of a word is the number of bits set to one. The fast idiom V := V and (V - 1) clears the lowest set bit, so the loop runs once per set bit rather than once per bit position. A parity bit is the xor of all bits, and it is 1 when the number of set bits is odd.

popcount.pas
program popcount;
{$mode objfpc}{$H+}

function PopCount(V: LongWord): Integer;
begin
  Result := 0;
  while V <> 0 do
  begin
    V := V and (V - 1);
    Inc(Result);
  end;
end;

function ParityBit(V: LongWord): Integer;
var
  B: Integer;
begin
  B := 0;
  while V <> 0 do
  begin
    B := B xor (V and 1);
    V := V shr 1;
  end;
  Result := B;
end;

var
  I: Integer;

begin
  for I := 0 to 15 do
    Write(PopCount(I), ' ');
  WriteLn;

  WriteLn('PopCount($F0F0) = ', PopCount($F0F0));
  WriteLn('ParityBit(7)   = ', ParityBit(7));
  WriteLn('ParityBit(3)   = ', ParityBit(3));
end.

The sequence 0, 1, 1, 2, 1, 2, 2, 3 for the first four values is the population count of 0..3. $F0F0 has eight set bits, four in each nonzero byte. Seven has three set bits, so its parity is 1; three has two set bits, so its parity is 0. Modern processors have a population-count instruction, but the portable loop is short and usually fast enough.

$ fpc -gl popcount.pas
$ ./popcount
0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4
PopCount($F0F0) = 8
ParityBit(7)   = 1
ParityBit(3)   = 0

Gray code

In Gray code, two consecutive values differ in exactly one bit. The encoding is N xor (N shr 1), and decoding repeatedly XORs the value with successively wider right shifts. Gray code is used in rotary encoders, in error-correcting codes, and in algorithms that enumerate combinations so that only one element changes at a time.

gray.pas
program gray;
{$mode objfpc}{$H+}

function GrayEncode(N: LongWord): LongWord;
begin
  Result := N xor (N shr 1);
end;

function GrayDecode(G: LongWord): LongWord;
var
  Shift: Integer;
begin
  Result := G;
  Shift := 1;
  while Shift < 32 do
  begin
    Result := Result xor (Result shr Shift);
    Shift := Shift * 2;
  end;
end;

var
  I: LongWord;

begin
  WriteLn('n   binary   gray    decoded');
  for I := 0 to 7 do
    WriteLn(I:2, '  ', BinStr(I, 3), '    ', BinStr(GrayEncode(I), 3),
      '     ', GrayDecode(GrayEncode(I)));
end.

The gray column changes by one bit from row to row: 000, 001, 011, 010, 110, 111, 101, 100. Decoding returns the original number for every row. The decoder loop shifts by 1, 2, 4, 8, and 16, so it finishes in five steps for a 32-bit word; the condition Shift < 32 prevents a shift by the word size, which would be undefined.

$ fpc -gl gray.pas
$ ./gray
n   binary   gray    decoded
 0  000    000     0
 1  001    001     1
 2  010    011     2
 3  011    010     3
 4  100    110     4
 5  101    111     5
 6  110    101     6
 7  111    100     7

Packing a colour

Bit fields are often packed into one integer to save space. A 24-bit RGB colour fits in a LongWord with red in bits 16..23, green in 8..15, and blue in 0..7. Packing shifts each component into place and combines them with or; unpacking shifts the word right and masks off the other components.

rgb.pas
program rgb;
{$mode objfpc}{$H+}

uses SysUtils;

function PackRGB(R, G, B: Byte): LongWord;
begin
  Result := (LongWord(R) shl 16) or (LongWord(G) shl 8) or LongWord(B);
end;

function RedOf(C: LongWord): Byte;
begin
  Result := (C shr 16) and $FF;
end;

function GreenOf(C: LongWord): Byte;
begin
  Result := (C shr 8) and $FF;
end;

function BlueOf(C: LongWord): Byte;
begin
  Result := C and $FF;
end;

var
  Color: LongWord;

begin
  Color := PackRGB(255, 128, 64);
  WriteLn('packed:  $', HexStr(Color, 8));
  WriteLn('red:     ', RedOf(Color));
  WriteLn('green:   ', GreenOf(Color));
  WriteLn('blue:    ', BlueOf(Color));
end.

The packed value is $00FF8040: 255 is $FF, 128 is $80, and 64 is $40. The casts to LongWord keep the expression unsigned and 32 bits wide; without them the shift may be performed in a signed integer type, which matters as soon as the high bit is set. The mask $FF removes the higher components after the shift, so the functions work even when the word contains other fields.

$ fpc -gl rgb.pas
$ ./rgb
packed:  $00FF8040
red:     255
green:   128
blue:    64

Signed and unsigned shifts

In Pascal, shr is a logical shift even for a signed integer: the vacated high bits are filled with zeros, not with copies of the sign bit. A negative Integer therefore becomes a large positive value after a right shift. To work with bit patterns, use an unsigned type such as Cardinal or LongWord and convert explicitly, which makes the intended interpretation clear.

signed.pas
program signed;
{$mode objfpc}{$H+}

var
  I: Integer;
  C: Cardinal;

begin
  I := -8;
  C := Cardinal(I);
  WriteLn('I = ', I);
  WriteLn('C = ', C);
  WriteLn('I shr 1 = ', I shr 1);
  WriteLn('C shr 1 = ', C shr 1);
  WriteLn('not 12  = ', not 12);
end.

-8 is $FFFFFFF8, so the unsigned value is 4,294,967,288, and a one-bit right shift gives 2,147,483,644 in both cases. not 12 is -13 because the result is interpreted as a signed integer again. A constant expression can be evaluated at a wider width than a variable; the operators article explains when that changes the printed value.

$ fpc -gl signed.pas
$ ./signed
I = -8
C = 4294967288
I shr 1 = 2147483644
C shr 1 = 2147483644
not 12  = -13

Bit sets with TBits

A Pascal set has at most 256 elements and its size is fixed at compile time. For larger or dynamic bit collections, the Classes unit provides TBits, a class that grows on demand and exposes indexed Boolean values. Internally it stores the bits in an array of integers, with one bit per element.

bits.pas
program bits;
{$mode objfpc}{$H+}

uses Classes;

var
  B: TBits;
  I, Count: Integer;

begin
  B := TBits.Create;
  try
    B.Size := 16;
    B[1] := True;
    B[4] := True;
    B[7] := True;
    B[9] := True;
    B[14] := True;

    Count := 0;
    Write('set bits: ');
    for I := 0 to B.Size - 1 do
      if B[I] then
      begin
        Write(I, ' ');
        Inc(Count);
      end;
    WriteLn;
    WriteLn('count: ', Count);
    WriteLn('size: ', B.Size);
  finally
    B.Free;
  end;
end.

Setting Size to a larger value preserves the existing bits and adds zeroed ones; shrinking drops the bits beyond the new size. Reading an index outside the current size raises EBitsError, while writing outside it grows the structure automatically. For a fixed-width bit mask that fits in a machine word, the integer operators shown earlier in this article are faster than either a set or TBits.

$ fpc -gl bits.pas
$ ./bits
set bits: 1 4 7 9 14
count: 5
size: 16

Next steps

The enumerations and sets article builds sets on the same masks, and the floating-point article shows how the sign, exponent, and mantissa of a real are laid out in bits. The memory management article explains the fixed-size values that the operators here work on, and the hash tables article uses bit mixing in its hash functions.

Source

Free Pascal Reference guide: expressions and operators

Free Pascal: BinStr

Gray code on Wikipedia

Free Pascal: TBits

In this article we combined bits with and, or, xor, and not, shifted them, wrote literals in three bases, built masks for flags, counted set bits, encoded and decoded Gray code, packed an RGB colour, compared signed and unsigned shifts, and stored a dynamic bit collection in TBits. The series continues with floating-point arithmetic in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.