How to round a number to the previous power of 2 in PHP

1 Answer

0 votes
/**
 * Rounds an integer down to the previous power of 2.
 *
 * return int The previous power of 2 less than or equal to $n
 */
function roundToPreviousPowerOf2(int $n): int {
    if ($n <= 0) {
        return 0;
    }
    
    return (int) pow(2, floor(log($n, 2)));
}

$num = 21;
echo "Previous power of 2: " . roundToPreviousPowerOf2($num) . PHP_EOL;



/*
run:

Previous power of 2: 16

*/

 



answered Oct 30, 2025 by avibootz

Related questions

2 answers 96 views
3 answers 201 views
1 answer 147 views
1 answer 76 views
1 answer 73 views
1 answer 74 views
...