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

1 Answer

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

        left  = bits above removed bit
        right = bits below removed bit

        result = (left << position) | right
*/
function removeBitAndShift(int $number, int $position): int {
    $left  = $number >> ($position + 1);          // bits above removed bit
    $right = $number & ((1 << $position) - 1);    // bits below removed bit

    return ($left << $position) | $right;         // merge shifted left + right
}

/*
    printBinary($value)
    -------------------
    PHP binary printing:
        decbin($value) → binary string
        str_pad(..., 32, '0', STR_PAD_LEFT) → pad to 32 bits
        chunk_split(..., 4, ' ') → group into 4-bit blocks
*/
function printBinary(int $value): void {
    $binary = decbin($value);
    $binary = str_pad($binary, 32, '0', STR_PAD_LEFT);
    $binary = chunk_split($binary, 4, ' ');
    echo $binary;
}

$number = 22;
$position = 2; // remove bit 2 (0 = LSB)

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

$result = removeBitAndShift($number, $position);

echo "\n\nNumber after removing bit $position and shifting remaining bits:\n";
printBinary($result);

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



/*
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 Jun 24 by avibootz
edited Jun 24 by avibootz

Related questions

...