How to remove multiple bits from a number and shift the remaining bits right to fill the gaps in Pascal

1 Answer

0 votes
program RemoveBitsAndShift;

{$mode objfpc}{$H+}

{
    removeBitsAndShift(number, positions, count)
    --------------------------------------------
    Removes multiple bit positions from a number and shifts the remaining bits
    right to fill the gaps.

    Important:
        Bits must be removed from highest → lowest position.
        Otherwise earlier removals shift the positions of later ones.
}

function removeBitsAndShift(number: LongInt; positions: array of Integer; count: Integer): LongInt;
var
    sorted: array of Integer;
    i, j, temp, pos: Integer;
    leftPart, rightPart: LongInt;
begin
    SetLength(sorted, count);

    { Copy positions }
    for i := 0 to count - 1 do
        sorted[i] := positions[i];

    { Sort descending }
    for i := 0 to count - 2 do
        for j := 0 to count - i - 2 do
            if sorted[j] < sorted[j + 1] then
            begin
                temp := sorted[j];
                sorted[j] := sorted[j + 1];
                sorted[j + 1] := temp;
            end;

    Result := number;

    { Remove bits from highest to lowest }
    for i := 0 to count - 1 do
    begin
        pos := sorted[i];

        leftPart  := Result shr (pos + 1);          { bits above removed bit }
        rightPart := Result and ((1 shl pos) - 1);  { bits below removed bit }

        Result := (leftPart shl pos) or rightPart;  { merge }
    end;
end;

{
    printBinary(n)
    --------------
    Prints a 32-bit binary representation of an integer.
}
procedure printBinary(n: LongInt);
var
    i: Integer;
begin
    for i := 31 downto 0 do
    begin
        Write((n shr i) and 1);
        if (i mod 4 = 0) then
            Write(' ');
    end;
end;

var
    number, result: LongInt;
    positions: array[0..2] of Integer = (1, 3, 7);
begin
    number := 1234;  { 0000 0000 0000 0000 0000 0100 1101 0010 }

    WriteLn('Original number in binary:');
    printBinary(number);

    result := removeBitsAndShift(number, positions, Length(positions));

    WriteLn;
    WriteLn;
    WriteLn('Number after removing bits {1, 3, 7} and shifting remaining bits:');
    printBinary(result);

    WriteLn;
    WriteLn;
    WriteLn('Result as integer: ', result);
end.



{
run:

Original number in binary:
0000 0000 0000 0000 0000 0100 1101 0010 

Number after removing bits (1, 3, 7) and shifting remaining bits:
0000 0000 0000 0000 0000 0000 1001 0100 

Result as integer: 148

}

 



answered 1 day ago by avibootz

Related questions

...