How to clear bits in the given range in Pascal

1 Answer

0 votes
program ClearBitsRange;

{$R+}  { enable range checking }

{ Print bits of a 32-bit integer }
procedure PrintBits(x: LongInt; labelStr: string);
var
    i: Integer;
begin
    Write(labelStr, ': ');
    for i := 31 downto 0 do
        Write((x shr i) and 1);
    Writeln;
end;

{ Clear bits in range [l, r] inclusive (0 = least significant bit) }
function ClearBits(x: LongInt; l, r: Integer): LongInt;
var
    maskLeft  : LongInt;
    maskRight : LongInt;
    mask      : LongInt;
begin
    if (l < 0) or (r > 31) or (l > r) then
    begin
        Writeln('Invalid bit range');
        Halt(1);
    end;

    { maskLeft:
      Create a mask with 1s above bit r and 0s from bit r down to 0.
      Example: r = 5 → maskLeft = 11111111 11111111 11111111 11000000 }
    maskLeft := LongInt($FFFFFFFF) shl (r + 1);
    PrintBits(maskLeft, 'maskLeft ');

    { maskRight:
      Create a mask with 1s below bit l and 0s from bit l upward.
      Example: l = 3 → maskRight = 00000000 00000000 00000000 00000111 }
    maskRight := (1 shl l) - 1;
    PrintBits(maskRight, 'maskRight');

    { Combine both masks:
      maskLeft keeps bits above r.
      maskRight keeps bits below l.
      The range [l, r] becomes 0s. }
    mask := maskLeft or maskRight;
    PrintBits(mask, 'mask     ');

    ClearBits := x and mask;
end;

var
    value  : LongInt;
    result : LongInt;
    l, r   : Integer;

begin
    { Turbo Pascal does not support binary literals,
      so we use hexadecimal for the same value: }
    value := LongInt($FCF3F3FC); { 11111100111111001111110011111100 }

    l := 3;   { start bit }
    r := 10;  { end bit }

    result := ClearBits(value, l, r);

    PrintBits(value,  'Before   ');
    PrintBits(result, 'After    ');
end.



(*
run:

maskLeft : 11111111111111111111100000000000
maskRight: 00000000000000000000000000000111
mask     : 11111111111111111111100000000111
Before   : 11111100111100111111001111111100
After    : 11111100111100111111000000000100

*)


 



answered Dec 29, 2025 by avibootz
...