Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to use Word data type (16-bit unsigned integer) to set and find set bits indexes in Pascal

1 Answer

0 votes
program BitSetDemo;

const
  BIT_SIZE = 16;

type
  TBitSet = Word;

// Print binary representation of the bitset 
procedure PrintBinary(bits: TBitSet);
var
  i: Integer;
begin
  for i := BIT_SIZE - 1 downto 0 do
    if (bits and (1 shl i)) <> 0 then
      Write('1')
    else
      Write('0');
  Writeln;
end;

function FindFirstSetBit(bits: TBitSet): Integer;
var
  i: Integer;
begin
  for i := 0 to BIT_SIZE - 1 do
    if (bits and (1 shl i)) <> 0 then
    begin
      FindFirstSetBit := i;
      Exit;
    end;
  FindFirstSetBit := -1;
end;

procedure PrintSetBitIndexes(bits: TBitSet);
var
  i: Integer;
begin
  for i := 0 to BIT_SIZE - 1 do
    if (bits and (1 shl i)) <> 0 then
      Write(i, ' ');
  Writeln;
end;

var
  bits: TBitSet;
  first: Integer;

begin
  bits := 0;
  bits := bits or (1 shl 3);
  bits := bits or (1 shl 5);
  bits := bits or (1 shl 11);
  bits := bits or (1 shl 14);

  PrintBinary(bits);

  first := FindFirstSetBit(bits);
  Writeln('First set bit at index: ', first);

  Writeln('All the set bits indexes:');
  PrintSetBitIndexes(bits);
end.




(*
run:

0100100000101000
First set bit at index: 3
All the set bits indexes:
3 5 11 14 

*)

 



answered Nov 3, 2025 by avibootz
...