How to create a bitset in Pascal

2 Answers

0 votes
// A set type that can be used to represent a bitset

program BitsetExample;

type
  TBitset = set of 0..31;  // Define a bitset with 32 bits

var
  bitset: TBitset;

// Function to print the bitset as 0 and 1 in reverse order
procedure PrintBitset(bits: TBitset);
var
  i: Integer;
begin
  for i := 31 downto 0 do  // Iterate in reverse order
  begin
    if i in bits then
      Write('1')
    else
      Write('0');
  end;
  WriteLn;
end;

begin
  bitset := [];  // Initialize the bitset to be empty

  // Set some bits
  Include(bitset, 1);
  Include(bitset, 3);
  Include(bitset, 5);

  // Print the bitset
  WriteLn('Bitset:');
  PrintBitset(bitset);

  // Clear a bit
  Exclude(bitset, 3);

  // Print the modified bitset
  WriteLn('Bitset after clearing bit 3:');
  PrintBitset(bitset);
end.



(*
run:

Bitset:
00000000000000000000000000101010
Bitset after clearing bit 3:
00000000000000000000000000100010

*)

 



answered May 7 by avibootz
0 votes
// Using Arrays of Boolean

program BitsetExample;

const
  BITSET_SIZE = 32;  // Define the size of the bitset

type
  TBitset = array[0..BITSET_SIZE-1] of Boolean;

// Function to print the bitset as 0 and 1 in reverse order
procedure PrintBitset(bits: TBitset);
var
  i: Integer;
begin
  for i := BITSET_SIZE - 1 downto 0 do  // Iterate in reverse order
  begin
    if bits[i] then
      Write('1')
    else
      Write('0');
  end;
  WriteLn;
end;

var
  bitset: TBitset;
  i: Integer;

begin
  // Initialize the bitset to be all false
  for i := 0 to BITSET_SIZE - 1 do
    bitset[i] := False;

  // Set some bits
  bitset[1] := True;
  bitset[3] := True;
  bitset[5] := True;

  // Print the bitset
  WriteLn('Bitset:');
  PrintBitset(bitset);

  // Clear a bit
  bitset[3] := False;

  // Print the modified bitset
  WriteLn('Bitset after clearing bit 3:');
  PrintBitset(bitset);
end.



(*
run:

Bitset:
00000000000000000000000000101010
Bitset after clearing bit 3:
00000000000000000000000000100010

*)

 



answered May 7 by avibootz
...