How to round a number to the previous power of 2 in C#

1 Answer

0 votes
using System;

class Program
{
    /// Rounds an integer down to the previous power of 2.
    /// <returns>The previous power of 2 less than or equal to n</returns>
    static int RoundToPreviousPowerOf2(int n) {
        if (n <= 0) {
            return 0;
        }

        return (int)Math.Pow(2, Math.Floor(Math.Log(n, 2)));
    }

    static void Main()
    {
        int num = 21;
        
        Console.WriteLine($"Previous power of 2: {RoundToPreviousPowerOf2(num)}");
    }
}



/*
run:

Previous power of 2: 16

*/

 



answered Oct 30, 2025 by avibootz

Related questions

1 answer 47 views
1 answer 57 views
4 answers 107 views
3 answers 285 views
1 answer 121 views
1 answer 67 views
...