How to round a number to the next power of 2 in VB.NET

1 Answer

0 votes
Imports System

Class Program
    Private Shared Function RoundToNextPowerOf2(ByVal n As Integer) As Integer
        If n <= 0 Then Return 1
			
        Return CInt(Math.Pow(2, Math.Ceiling(Math.Log(n, 2))))
    End Function

    Public Shared Sub Main()
        Dim num As Integer = 21
			
        Console.WriteLine($"Next power of 2: {RoundToNextPowerOf2(num)}")
    End Sub
End Class

	
' run:
'
' Next power of 2: 32
'

 



answered 15 hours ago by avibootz

Related questions

...