How to remove a bit from a number and shift all bits to the right to fill the gap in Pascal

1 Answer

0 votes
program RemoveBitAndShift;

{
    removeBitAndShift(number, position)
    -----------------------------------
    Removes the bit at the given position and shifts all higher bits right.

    Example:
        number = 22 (10110)
        position = 2 (0 = LSB)

        Bits: 1 0 1 1 0
                  ^ remove this bit (bit 2)

        Split:
            left  = bits above the removed bit
            right = bits below the removed bit

        left << position   moves the left part down by one bit
        result = (left << position) OR right
}

function removeBitAndShift(number, position: LongInt): LongInt;
var
    left, right: LongInt;
begin
    left  := number shr (position + 1);              { bits above removed bit }
    right := number and ((1 shl position) - 1);      { bits below removed bit }

    removeBitAndShift := (left shl position) or right; { merge shifted left + right }
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, position, result: LongInt;

begin
    number := 22;
    position := 2;  { remove bit 2 (0 = LSB) }

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

    result := removeBitAndShift(number, position);

    WriteLn;
    WriteLn;
    WriteLn('Number after removing bit ', position, ' and shifting remaining bits:');
    printBinary(result);

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



{
run:

Original number in binary:
0000 0000 0000 0000 0000 0000 0001 0110 

Number after removing bit 2 and shifting remaining bits:
0000 0000 0000 0000 0000 0000 0000 1010 

Result as integer: 10

}

 



answered 3 hours ago by avibootz

Related questions

...