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

1 Answer

0 votes
/*
    removeBitsAndShift($number, $positions)
    ---------------------------------------
    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(int $number, array $positions): int
{
    // Sort positions descending
    rsort($positions);

    $result = $number;

    foreach ($positions as $pos) {

        $left  = $result >> ($pos + 1);          // bits above removed bit
        $right = $result & ((1 << $pos) - 1);    // bits below removed bit

        $result = ($left << $pos) | $right;      // merge
    }

    return $result;
}

/*
    printBinary($n)
    ---------------
    Prints a 32-bit binary representation of an integer.
*/
function printBinary(int $n): void
{
    $binary = str_pad(decbin($n), 32, "0", STR_PAD_LEFT);

    // Group into 4-bit chunks
    $binary = trim(chunk_split($binary, 4, " "));

    echo $binary . PHP_EOL;
}

// Main program
$number = 1234;              // 0000 0000 0000 0000 0000 0100 1101 0010
$positions = [1, 3, 7];      // remove bits 1, 3, 7 (0 = LSB)

echo "Original number in binary:\n";
printBinary($number);

$result = removeBitsAndShift($number, $positions);

echo "\nNumber after removing bits {1, 3, 7} and shifting remaining bits:\n";
printBinary($result);

echo "\nResult as integer: $result\n";



/*
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

...